【发布时间】:2014-01-09 16:24:50
【问题描述】:
我正在使用 RPC(远程过程调用)制作服务器-客户端程序。客户端向服务器发送三个数字,服务器计算数字的总和,如果它大于当前总和,则服务器将这三个数字发回给客户端。但我希望服务器发回客户端的端口和 IP,但我不知道该怎么做。有没有简单的方法来解决这个问题?
这是我的代码:
headerrpc.h
#include <rpc/rpc.h>
#include <rpc/xdr.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#define PROGRAM_EXEC ((u_long)0x40000000)
#define VERSIUNE_EXEC ((u_long)1)
#define EXEC_ADD ((u_long)2)
typedef struct Data{
short a;
short b;
short c;
u_short port;
}Data;
int xdr_Data(XDR* xdr, Data* d){
if(xdr_short(xdr,&(d->a)) == 0) return 0;
if(xdr_short(xdr,&(d->b)) == 0) return 0;
if(xdr_short(xdr,&(d->c)) == 0) return 0;
if(xdr_short(xdr,&(d->port)) == 0) return 0;
return 1;
}
服务器
#include "headerrpc.h"
#include <stdio.h>
#include <stdlib.h>
Data* data;
Data* add(Data* d){
static int sum = -32000;
//Data* data = (Data*)malloc(sizeof(Data));
if((d->a + d->b + d->c) > sum)
{
sum = d->a + d->b + d->c;
data->a = d->a;
data->b = d->b;
data->c = d->c;
data->port = data->port;
printf("It was found a greater sum %d\n");
return data;
}
else
{
printf("The sum of the given numbers is not greater than the current sum\n");
return data;
}
}
main(){
data = (Data*)malloc(sizeof(Data));
registerrpc(PROGRAM_EXEC, VERSIUNE_EXEC, EXEC_ADD, add, xdr_Data, xdr_Data);
svc_run();
}
客户
#include "headerrpc.h"
#include <stdio.h>
#include <stdlib.h>
int main()
{
Data d;
Data* r = (Data*)malloc(sizeof(Data));
int suma;
printf("Client\n");
int a, b, c;
printf("Type the first number: ");
scanf("%d",&a);
printf("Type the second number: ");
scanf("%d",&b);
printf("Type the third number: ");
scanf("%d",&c);
d.a = a;
d.b = b;
d.c = c;
d.port = serv_addr.sin_port;
callrpc("localhost",PROGRAM_EXEC, VERSIUNE_EXEC,EXEC_ADD,(xdrproc_t)xdr_Data,(char*)&d,(xdrproc_t)xdr_Data,(char*)r);
printf("The numbers with the greater sum are: %d, %d, %d\n", r->a,r->b,r->c);
}
【问题讨论】: