server端代码:
#include <stdio.h>
#include <rpc/rpc.h>
#include <rpcsvc/rusers.h>
void nuser(struct svc_req * rqstp, SVCXPRT * transp)
{
unsigned nusers;
unsigned input;
switch (rqstp->rq_proc) {
case NULLPROC:
if (!svc_sendreply(transp, xdr_void, 0)) {
fprintf(stderr, "can't reply to RPC call\n");
exit(1);
}
return;
case RUSERSPROC_NUM:
/* Code here to compute the number of users and
* assign to the variable nusers
*/
if(!svc_getargs(transp,xdr_int,&input))
{
svcerr_decode(transp);
return ;
}
fprintf(stderr,"This is the lowest layer of RPC!! and recieve data is %u\n",input);
nusers = (unsigned)10 + input;
if (!svc_sendreply(transp, xdr_u_long, &nusers)) {
fprintf(stderr, "can't reply to RPC call\n");
exit(1);
}
return;
default:
svcerr_noproc(transp);
return;
}
}
int main(void)
{
SVCXPRT *transp;
void nuser();
transp = svcudp_create(RPC_ANYSOCK);
if (transp == NULL){
fprintf(stderr, "can't create an RPC server\n");
exit(1);
}
pmap_unset(RUSERSPROG, RUSERSVERS);
if (!svc_register(transp, RUSERSPROG, RUSERSVERS, nuser,
IPPROTO_UDP)) {
fprintf(stderr, "can't register RUSER service\n");
exit(1);
}
svc_run(); /* never returns */
fprintf(stderr, "should never reach this point\n");
exit(1);
}
client端代码:
/*
* howmany3.c
*/
#include <stdio.h>
#include <rpc/rpc.h>
#include <rpcsvc/rusers.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <netdb.h>
main(int argc, char **argv)
{
struct hostent *hp;
struct timeval pertry_timeout, total_timeout;
struct sockaddr_in server_addr;
int sock = RPC_ANYSOCK;
register CLIENT *client;
enum clnt_stat clnt_stat;
unsigned nusers;
unsigned input = 10;
if (argc != 2) {
fprintf(stderr, "usage: howmany3 hostname\n");
exit(1);
}
if ((hp = gethostbyname(argv[1])) == NULL) {
herror(argv[1]);
exit(1);
}
pertry_timeout.tv_sec = 3;
pertry_timeout.tv_usec = 0;
bcopy(hp->h_addr, (caddr_t)&server_addr.sin_addr,
hp->h_length);
server_addr.sin_family = AF_INET;
server_addr.sin_port = 0;
if ((client = clntudp_create(&server_addr, RUSERSPROG,
RUSERSVERS, pertry_timeout, &sock)) == NULL) {
clnt_pcreateerror("clntudp_create");
exit(1);
}
total_timeout.tv_sec = 20;
total_timeout.tv_usec = 0;
clnt_stat = clnt_call(client,RUSERSPROC_NUM,xdr_u_int,&input,
xdr_u_int,&nusers, total_timeout);
if (clnt_stat != RPC_SUCCESS) {
clnt_perror(client, "rpc");
exit(1);
}
printf("%d users on %s\n", nusers, argv[1]);
clnt_destroy(client);
close(sock);
exit(0);
}