用于远程过程的端口和ip调用unix

时间:2014-01-09 16:24:50

标签: c linux rpc

我正在使用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);
}

1 个答案:

答案 0 :(得分:0)

默认服务器例程实际上采用第二个参数struct svc_req *rqstp,从中可以确定客户端的IP地址。

所以你的添加函数定义应如下所示:

Data* add(Data* d, struct svc_req *rqstp) {

您可以从rqstp->rq_xprt->xp_raddr.sin_addr成员确定客户端的IP地址,同样可以从rqstp->rq_xprt->xp_raddr.sin_port成员确定端口。

因为您正在使用registerrpc,这意味着该服务仅在UDP上可用,并且无法通过IPv6使用,这意味着该地址是32位值,这对于返回。

我没有足够的RPC over IPv6经验,无法给出我知道在这种情况下可以解决的答案。

相关问题