[ Team LiB ] Previous Section Next Section

Chapter 11

11.1

Figure E.10 shows our program that calls gethostbyaddr. This program works fine for a host with a single IP address. If we run the program in Figure 11.3 for a host with four IP addresses, we get the following:

freebsd % hostent cnn.com
official hostname: cnn.com
        address: 64.236.16.20
        address: 64.236.16.52
        address: 64.236.16.84
        address: 64.236.16.116
        address: 64.236.24.4
        address: 64.236.24.12
        address: 64.236.24.20
        address: 64.236.24.28

But if we run the program in Figure E.10 for the same host, only the first IP address is output as follows:

freebsd % hostent2 cnn.com
official hostname: cnn.com
        address: 64.236.24.4
        name = www1.cnn.com

Figure E.10 Modification to Figure 11.3 to call gethostbyaddr.

names/hostent2.c

 1 #include    "unp.h"

 2 int
 3 main(int argc, char **argv)
 4 {
 5     char   *ptr, **pptr;
 6     char    str[INET6_ADDRSTRLEN];
 7     struct hostent *hptr;

 8     while (--argc > 0) {
 9         ptr = *++argv;
10         if ( (hptr = gethostbyname(ptr)) == NULL) {
11             err_msg("gethostbyname error for host: %s: %s",
12                     ptr, hstrerror(h_errno));
13             continue;
14         }
15         printf("official hostname: %s\n", hptr->h_name);

16         for (pptr = hptr->h_aliases; *pptr != NULL; pptr++)
17             printf("    alias: %s\n", *pptr);

18         switch (hptr->h_addrtype) {
19         case AF_INET:
20 #ifdef  AF_INET6
21         case AF_INET6:
22 #endif
23             pptr = hptr->h_addr_list;
24             for ( ; *pptr != NULL; pptr++) {
25                 printf("\taddress: %s\n",
26                        Inet_ntop(hptr->h_addrtype, *pptr, str, sizeof(str)));

27                 if ( (hptr = gethostbyaddr(*pptr, hptr->h_length,
28                                           hptr->h_addrtype)) == NULL)
29                     printf("\t(gethostbyaddr failed)\n");
30                     else if (hptr->h_name != NULL)
31                         printf("\tname = %s\n", hptr->h_name);
32                     else
33                         printf("\t(no hostname returned by gethostbyaddr)\n");
34             }
35             break;

36         default:
37             err_ret("unknown address type");
38             break;
39         }
40     }
41     exit(0);
42 }

The problem is that the two functions, gethostbyname and gethostbyaddr, share the same hostent structure, as we show at the beginning of Section 11.18. When our new program calls gethostbyaddr, it reuses this structure, along with the storage that the structure points to (i.e., the h_addr_list array of pointers), wiping out the remaining three IP addresses returned by gethostbyname.

11.2

If your system does not supply the re-entrant version of gethostbyaddr (which we describe in Section 11.19), then you must make a copy of the array of pointers returned by gethostbyname, along with the data pointed to by this array, before calling gethostbyaddr.

11.3

The chargen server sends data to the client until the client closes the connection (i.e., until you abort the client).

11.4

This is a feature of some resolvers, but you cannot rely on it in a portable program because POSIX leaves the behavior unspecified. Figure E.11 shows the modified version. The order of the tests on the hostname string is important. We call inet_pton first, as it is a fast, in-memory test for whether or not the string is a valid dotted-decimal IP address. Only if this fails do we call gethostbyname, which typically involves some network resources and some time.

If the string is a valid dotted-decimal IP address, we make our own array of pointers (addrs) to the single IP address, allowing the loop using pptr to remain the same.

Since the address has already been converted to binary in the socket address structure, we change the call to memcpy in Figure 11.4 to call memmove instead, because when a dotted-decimal IP address is entered, the source and destination fields are the same in this call.

Figure E.11 Allow dotted-decimal IP address or hostname, port number, or service name.

names/daytimetcpcli2.c

 1 #include    "unp.h"

 2 int
 3 main(int argc, char **argv)
 4 {
 5     int     sockfd, n;
 6     char    recvline[MAXLINE + 1];
 7     struct sockaddr_in servaddr;
 8     struct in_addr **pptr, *addrs[2];
 9     struct hostent *hp;
10     struct servent *sp;

11     if (argc != 3)
12         err_quit("usage: daytimetcpcli2 <hostname> <service>");

13     bzero(&servaddr, sizeof(servaddr));
14     servaddr.sin_family = AF_INET;

15     if (inet_pton(AF_INET, argv[1], &servaddr.sin_addr) == 1) {
16         addrs[0] = &servaddr.sin_addr;
17         addrs[1] = NULL;
18         pptr = &addrs[0];
19     } else if ((hp = gethostbyname(argv[1])) != NULL) {
20         pptr = (struct in_addr **) hp->h_addr_list;
21     } else
22          err_quit("hostname error for %s: %s", argv[1], hstrerror(h_errno));

23     if ( (n = atoi(argv[2])) > 0)
24         servaddr.sin_port = htons(n);
25     else if ((sp = getservbyname(argv[2], "tcp")) != NULL)
26         servaddr.sin_port = sp->s_port;
27     else
28         err_quit("getservbyname error for %s", argv[2]);

29     for ( ; *pptr != NULL; pptr++) {
30         sockfd = Socket(AF_INET, SOCK_STREAM, 0);

31         memmove(&servaddr.sin_addr, *pptr, sizeof(struct in_addr));
32         printf("trying %s\n", Sock_ntop((SA *) &servaddr, sizeof(servaddr)));
33         if (connect(sockfd, (SA *) &servaddr, sizeof(servaddr)) == 0)
34             break;              /* success */
35          err_ret("connect error");
36          close(sockfd);
37     }
38     if (*pptr == NULL)
39         err_quit("unable to connect");

40     while ( (n = Read(sockfd, recvline, MAXLINE)) > 0) {
41         recvline[n] = 0;        /* null terminate */
42         Fputs(recvline, stdout);
43     }
44     exit(0);
45     }

11.5

Figure E.12 shows the program.

Figure E.12 Modification of Figure 11.4 to work with IPv4 and IPv6.

names/daytimetcpcli3.c

 1 #include   "unp.h"

 2 int
 3 main(int argc, char **argv)
 4 {
 5     int     sockfd, n;
 6     char    recvline[MAXLINE + 1];
 7     struct sockaddr_in servaddr;
 8     struct sockaddr_in6 servaddr6;
 9     struct sockaddr *sa;
10     socklen_t salen;
11     struct in_addr **pptr;
12     struct hostent *hp;
13     struct servent *sp;

14     if (argc != 3)
15         err_quit("usage: daytimetcpcli3  <hostname> <service>");

16     if ( (hp = gethostbyname(argv[1])) == NULL)
17         err_quit("hostname error for %s: %s", argv[1], hstrerror(h_errno));

18     if ( (sp = getservbyname(argv[2], "tcp")) == NULL)
19         err_quit("getservbyname error for %s", argv[2]);
20     pptr = (struct in_addr **) hp->h_addr_list;
21     for ( ; *pptr != NULL; pptr++) {
22         sockfd = Socket(hp->h_addrtype, SOCK_STREAM, 0);

23         if (hp->h_addrtype == AF_INET) {
24             sa = (SA *) &servaddr;
25             salen = sizeof(servaddr);
26         } else if (hp->h_addrtype == AF_INET6) {
27             sa = (SA *) &servaddr6;
28             salen = sizeof(servaddr6);
29         } else
30             err_quit("unknown addrtype %d", hp->h_addrtype);

31         bzero(sa, salen);
32         sa->sa_family = hp->h_addrtype;
33         sock_set_port(sa, salen, sp->s_port);
34         sock_set_addr(sa, salen, *pptr);

35         printf("trying %s\n", Sock_ntop(sa, salen));

36         if (connect(sockfd, sa, salen) == 0)
37             break;              /* success */
38         err_ret("connect error");
39         close(sockfd);
40     }
41     if (*pptr == NULL)
42         err_quit("unable to connect");

43     while ( (n = Read(sockfd, recvline, MAXLINE)) > 0) {
44         recvline[n] = 0;        /* null terminate */
45         Fputs(recvline, stdout);
46     }
47     exit(0);
48     }

We use the h_addrtype value returned by gethostbyname to determine the type of address. We also use our sock_set_port and sock_set_addr functions (Section 3.8) to set these two fields in the appropriate socket address structure.

Although this program works, it has two limitations. First, we must handle all the differences, looking at h_addrtype and then setting sa and salen appropriately. A better solution is to have a library function that not only looks up the hostname and service name, but also fills in the entire socket address structure (e.g., getaddrinfo in Section 11.6). Second, this program compiles only on hosts that support IPv6. To make this compile on an IPv4-only host would add numerous #ifdefs to the code, thus complicating it.

We return to the concept of protocol independence in Chapter 11 and see better ways to accomplish it.

11.7

Allocate a big buffer (larger than any socket address structure) and call getsockname. The third argument is a value-result argument that returns the actual size of the protocol's addresses. Unfortunately, this works only for protocols with fixed-length socket address structures (e.g., IPv4 and IPv6), but is not guaranteed to work with protocols that can return variable-length socket address structures (e.g., Unix domain sockets, Chapter 15).

11.8

We first allocate arrays to hold the hostname and service name as follows:

char host[NI_MAXHOST], serv[NI_MAXSERV];

After accept returns, we call getnameinfo instead of sock_ntop as follows:

if (getnameinfo(cliaddr, len, host, NI_MAXHOST, serv, NI_MAXSERV,
                NI_NUMERICHOST | NI_NUMERICSERV) == 0)
printf("connection from %s.%s\n", host, serv);

Since this is a server, we specify the NI_NUMERICHOST and NI_NUMERICSERV flags to avoid a DNS query and a lookup of /etc/services.

11.9

The first problem is that the second server cannot bind the same port as the first server because the SO_REUSEADDR socket option is not set. The easiest way to handle this is to make a copy of the udp_server function, rename it udp_server_reuseaddr, have it set the socket option, and call this new function from the server.

11.10

When the client outputs "Trying 206.62.226.35...", gethostbyname has returned the IP address. Any client pause before this is the time taken by the resolver to look up the hostname. The output "Connected to bsdi.kohala.com." means connect has returned. Any pause between these two lines of output is the time taken by connect to establish the connection.


    [ Team LiB ] Previous Section Next Section