This example is a C/SProgramThere are four files: ruptime. c clconn. c ruptimed. c initsrv1.c, where ruptime. C and clconn. C constitutes the client, ruptimed. c initsrv1.c is a server. The client sends a request to the server. After receiving the request, the server runs the uptime command and returns the result to the client. The compilation and running methods are as follows:
1.Edit the/etc/services file and append the file.
Ruptime 4000/tcp # example program of apue2
Restart the system, so that the system adds a new service ruptime, and the assigned port number is 4000. Then we call the function in ruptime. C.
Getaddrinfo (argv [1], "ruptime", & hint, & ailist)
In order to succeed, and return the address information corresponding to the host and service. Similarly, the function call in ruptimed. c
Getaddrinfo (host, "ruptime", & hint, & ailist)
It can also work correctly.
The prototype of the getaddrinfo function is:
Int getaddrinfo ( Const char * Host
Const char * Service
Const struct addrinfo * hints, Struct addrinfo ** res );
The function maps a host name and service name to an address. That is, if the host name and service name are specified, the function returns
Address information of the host and service, which is stored in the res parameter. Res is a struct addrinfo
Prototype:
Struct addrinfo {
Int ai_flags;
Int ai_family;
Int ai_socktype;
Int ai_protocol
Socklen_t ai_addrlen;
Struct sockaddr * ai_addr;
Char * ai_canonname;
Struct addrinfo * ai_next;
}
2. Compile and run
Apue2> gcc-O ruptime. c clconn. c libapue.
Apue2> gcc-O ruptimed. c initsrv1.c libapue.
Apue2>./ruptimed
Apue2>./ruptime localhost
09:15:53 up 28 min, 2 users, load average: 0.10, 0.22, 0.18
Apue2>