The Linux Programming Interface

(nextflipdebug5) #1
Sockets: Internet Domains 1233

Listing 59-10 demonstrates the use of gethostbyname(). This program displays hostent
information for each of the hosts named on its command line. The following shell
session demonstrates the use of this program:


$ ./t_gethostbyname http://www.jambit.com
Canonical name: jamjam1.jambit.com
alias(es): http://www.jambit.com
address type: AF_INET
address(es): 62.245.207.90

Listing 59-10: Using gethostbyname() to retrieve host information


––––––––––––––––––––––––––––––––––––––––––––––––– sockets/t_gethostbyname.c
#define _BSD_SOURCE / To get hstrerror() declaration from <netdb.h> /
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "tlpi_hdr.h"


int
main(int argc, char argv[])
{
struct hostent
h;
char **pp;
char str[INET6_ADDRSTRLEN];


for (argv++; argv != NULL; argv++) {
h = gethostbyname(
argv);
if (h == NULL) {
fprintf(stderr, "gethostbyname() failed for '%s': %s\n",
*argv, hstrerror(h_errno));
continue;
}


printf("Canonical name: %s\n", h->h_name);


printf(" alias(es): ");
for (pp = h->h_aliases; pp != NULL; pp++)
printf(" %s",
pp);
printf("\n");


#define _BSD_SOURCE /* Or _SVID_SOURCE or _GNU_SOURCE */
#include <netdb.h>

void herror(const char *str);

const char *hstrerror(int err);
Returns pointer to h_errno error string corresponding to err
Free download pdf