Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 16.5 Data Transfer 615


err_exit(err, "can’t connect to %s", argv[1]);
}

Figure 16.16 Client command to get uptime from server

This program connects to a server,reads the string sent by the server,and prints the
string on the standardoutput. Since we’reusing aSOCK_STREAMsocket, we can’t be
guaranteed that we will read the entirestring in one call torecv, so we need to repeat
the call until it returns 0.
Thegetaddrinfofunction might return morethan one candidate address for us
to use if the server supports multiple network interfaces or multiple network protocols.
We try each one in turn, giving up when we find one that allows us to connect to the
service. Weuse the connect_retry function from Figure16.11 to establish a
connection with the server.

Example — Connection-Oriented Ser ver


Figure16.17 shows the server that provides theuptimecommand’s output to the client
program from Figure16.16.
#include "apue.h"
#include <netdb.h>
#include <errno.h>
#include <syslog.h>
#include <sys/socket.h>
#define BUFLEN 128
#define QLEN 10
#ifndef HOST_NAME_MAX
#define HOST_NAME_MAX 256
#endif
extern int initserver(int, const struct sockaddr *, socklen_t, int);
void
serve(int sockfd)
{
int clfd;
FILE *fp;
char buf[BUFLEN];
set_cloexec(sockfd);
for (;;) {
if ((clfd = accept(sockfd, NULL, NULL)) < 0) {
syslog(LOG_ERR, "ruptimed: accept error: %s",
strerror(errno));
exit(1);
}
set_cloexec(clfd);
if ((fp = popen("/usr/bin/uptime", "r")) == NULL) {
Free download pdf