最近在看unix网络编程卷二,在看到sun rpc那一部分的时候,发现几个问题,我是在ibm AIX上面开发,才发现原来真的是不同的UNIX系统差别真的很大,不多说,先上程序,包括三个文件,一个是RPC说明文件,另一个是客户端程序,还有一个是服务端程序。
1,RPC说明文件square.x
struct square_in { /* data */ long arg1; }; struct square_out { /* data */ long res1; }; program SQUARE_PROG{ version SQUARE_VERS{ square_out SQUAREPROC( square_in ) = 1; } = 1; } = 0x31230000;
2,客户端程序client.c
#include <stdlib.h> #include <rpc/rpc.h> #include "square.h" #include <errno.h> #include <stdio.h> int main (int argc, char const* argv[]) { CLIENT *cl; square_in in; square_out *outp; if( argc != 3 ){ perror("usage: client <hostname> <integer_value"); } cl = clnt_create( argv[1], SQUARE_PROG, SQUARE_VERS, "tcp"); auth_destroy( cl->cl_auth ); cl->cl_auth = authsys_create_default(); in.arg1 = atol( argv[2] ); if( ( outp = squareproc_1( &in, cl ) ) == NULL ) { printf("%s", clnt_sperror( cl, argv[1]) ); } printf("result: %ld/n", outp -> res1 ); return 0; }
3,服务端程序server.c
#include "square.h"
square_out * squareproc_1( square_in *inp, struct svc_req *rqstp ){
static square_out out;
if (rqstp->rq_cred.oa_flavor == 1) {
struct authunix_parms *au;
au = (struct authunix_parms *)rqstp->rq_clntcred;
printf("AUTH_SYS: host %s, uid %ld, gid %ld/n", au->aup_machname, (long) au->aup_uid, (long) au->aup_gid);
}
out.res1 = inp -> arg1 * inp -> arg1;
return (&out);
}
程序编译运行过程:
1, rpcgen square.x
生成square.h, square_clnt.c, square_svc.c,square_xdr.c
2, gcc server.c square_svc.c square_xdr.c -o server -lnsl
3, gcc client.c square_clnt.c square_xdr.c -o client -lnsl
4, ./server
5, ./client localhost 5
程序运行结果:
client:
result: 25
server:
AUTH_SYS: host root, uid 0, gid 0
注意点:
1,在UNIX网络编程一书中将square_out * squareproc_1( square_in *inp, struct svc_req *rqstp )写成是square_out * squareproc_1_svc( square_in *inp, struct svc_req *rqstp ),经过对比源程序,发现在AIX中应该去掉
2, 在UNIX网络编程中将au = (struct authunix_parms *)rqstp->rq_clntcred;写成au = ( struct authsys_parms * )rqstp->rq_clntcred;,在AIX中得用前者,因为后者是用的Solaris