C language RPC call Hello World example

1. Code

mkdir testcrpc
cd testcrpc
vi test.x

The content of test.x is as follows

program TESTPROG {
   version VERSION {
     string TEST(string) = 1;
   } = 1;
} = 87654321;

Generate code with rpcgen

rpcgen test.x

Get the file as follows

test_clnt.c  test.h  test_svc.c

Regenerate test_clnt_func.c

rpcgen -Sc -o test_clnt_func.c test.x

Regenerate test_srv_func.c

rpcgen -Ss -o test_srv_func.c test.x

Compile the server program

gcc -Wall -o test_server  test_srv_func.c test_svc.c

Compile the client program

gcc -Wall -o test_client test_clnt_func.c test_clnt.c

Start the server

./test_server

start the client

./test_client 127.0.0.1

2. Error resolution

error one

Cannot register service: RPC: Unable to receive; errno = Connection refused

because portmap is not installed

sudo apt-get install portmap
sudo service portmap start

error two

Cannot register service: RPC: Authentication error; why = Client credential too weak
unable to register (TESTPROG, VERSION, udp)

solve

sudo -i service portmap stop
sudo -i rpcbind -i -w
sudo -i service portmap start

error three

At this time, start the server and start the client, the client will report the following error

call failed: RPC: Remote system error

test_clnt_func.c

void
testprog_1(char *host)
{
     CLIENT *clnt;
     char * *result_1;
     char * test_1_arg;

#ifndef    DEBUG
     clnt = clnt_create (host, TESTPROG, VERSION, "udp");
     if (clnt == NULL) {
         clnt_pcreateerror (host);
         exit (1);
     }
#endif    /* DEBUG */

    result_1 = test_1(&test_1_arg, clnt);
     if (result_1 == (char **) NULL) {
         clnt_perror (clnt, "call failed");
     }
     if (strcmp(*result_1, "Error") == 0) {
                 fprintf(stderr, "%s: could not get the time\n", host);
                 exit(1);
     }
     printf("收到消息 ... %s\n", *result_1);

    
#ifndef    DEBUG
     clnt_destroy (clnt);
#endif     /* DEBUG */
}

test_srv_func.c

#include "test.h"#include <time.h>



char **
test_1_svc(char **argp, struct svc_req *rqstp)
{
    static char * result;

    static char tmp_char[128];
    time_t rawtime;

    /*
     * insert server code here
     */

    if( time(&rawtime) == ((time_t)-1) ) {
                strcpy(tmp_char, "Error");
                result = tmp_char;
                return &result;
    }
    sprintf(tmp_char, "The current server time is: %s " , ctime(& rawtime));
    result = tmp_char;

    return &result;
}

3. Results

Received the message... The current server time is: Mon Apr 23 19:03:34 2018

4. Reference

The above example is excerpted from the blog: https://blog.csdn.net/hj19870806/article/details/8185604

Mainly to record running errors.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324771887&siteId=291194637