Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 16.6 Socket Options 623


if (argc != 1)
err_quit("usage: ruptimed");
if ((n = sysconf(_SC_HOST_NAME_MAX)) < 0)
n=HOST_NAME_MAX; /* best guess */
if ((host = malloc(n)) == NULL)
err_sys("malloc error");
if (gethostname(host, n) < 0)
err_sys("gethostname error");
daemonize("ruptimed");
memset(&hint, 0, sizeof(hint));
hint.ai_flags = AI_CANONNAME;
hint.ai_socktype = SOCK_DGRAM;
hint.ai_canonname = NULL;
hint.ai_addr = NULL;
hint.ai_next = NULL;
if ((err = getaddrinfo(host, "ruptime", &hint, &ailist)) != 0) {
syslog(LOG_ERR, "ruptimed: getaddrinfo error: %s",
gai_strerror(err));
exit(1);
}
for (aip = ailist; aip != NULL; aip = aip->ai_next) {
if ((sockfd = initserver(SOCK_DGRAM, aip->ai_addr,
aip->ai_addrlen, 0)) >= 0) {
serve(sockfd);
exit(0);
}
}
exit(1);
}

Figure 16.20Server providing system uptime over datagrams

The server blocks inrecvfromfor a request for service. When a request arrives, we
save the requester ’s address and usepopento run theuptimecommand. Wesend the
output back to the client using thesendtofunction, with the destination address set to
the requester ’s address.

16.6 SocketOptions


The socket mechanism provides two socket-option interfaces for us to control the
behavior of sockets. One interface is used to set an option, and another interface allows
us to query the state of an option.We can get and set three kinds of options:


  1. Generic options that work with all socket types

  2. Options that aremanaged at the socket level, but depend on the underlying
    protocols for support

  3. Protocol-specific options unique to each individual protocol
    The Single UNIX Specification defines only the socket-layer options (the first two option
    types in the preceding list).

Free download pdf