[ Team LiB ] Previous Section Next Section

11.11 host_serv Function

Our first interface to getaddrinfo does not require the caller to allocate a hints structure and fill it in. Instead, the two fields of interest, the address family and the socket type, are arguments to our host_serv function.

#include "unp.h"

struct addrinfo *host_serv (const char *hostname, const char *service, int family, ints socktype);

Returns: pointer to addrinfo structure if OK, NULL on error

Figure 11.9 shows the source code for this function.

Figure 11.9 host_serv function.

lib/host_serv.c

 1  #include    "unp.h"

 2  struct addrinfo *
 3  host_serv(const char *host, const char *serv, int family, int socktype)
 4  {
 5    int     n;
 6    struct addrinfo hints, *res;

 7    bzero (&hints, sizeof (struct addrinfo));
 8    hints.ai_flags = AI_CANONNAME;   /* always return canonical name */
 9    hints.ai_family = family;   /* AF_UNSPEC, AF_INET, AF_INET6, etc. */
10    hints.ai_socktype = socktype;  /* 0, SOCK_STREAM, SOCK_DGRAM, etc. */

11    if ( (n = getaddrinfo(host, serv, &hints, &res)) != 0)
12        return (NULL);
13    return (res);              /* return pointer to first on linked list */
14 }

7–13 The function initializes a hints structure, calls getaddrinfo, and returns a null pointer if an error occurs.

We will call this function from Figure 16.17 when we want to use getaddrinfo to obtain the host and service information, but we want to establish the connection ourself.

    [ Team LiB ] Previous Section Next Section