DOCUMENT ID: 1101-02 SYNOPSIS: Sample program for using gethostbyname OS RELEASE: 2.1, 2.4, 2.5 PRODUCT: Solaris KEYWORDS: gethostbyname function hostent structure host name DESCRIPTION: This program demonstrates the use of gethostbyname function. SOLUTION: The function gethostbyname returns a pointer to a hostent structure. One of the most common uses of the function is converting a host string to an ip address. Conversion to an alias is also possible. struct hostent { char *h_table; /* official host name */ char **h_aliases; /* AKA's */ char h_addrtype; /* host address type */ char h_length; /* address length always 4 */ char **h_addr_list; /* name server supplied list list */ }; "h_table" points to a static string which containing the host name. "h_aliases" points to an array of addresses of alias strings. "h_addr_type" address type is hardcoded to AF_INET (internet) "h_length" is always 4. "h_addr_list" points to an array of pointers to in_addr structures. Each struct is one 32 bit ip address. The list is terminated by a NULL pointer. Note that all "**" lists have a null entry to terminate. The structure contents are actually filled in by a subordinate function, "gethostent", retrieving data from the /etc/hosts file. Just as a quick review "char **xx" is a pointer the address of a character pointer. Recall that the familiar "argv" parameter commonly used in "main declarations" is coded in either of two ways: char **argv; /* a pointer to a pointer of a string */ char *argv[]; /* an array of pointers to strings */ The sample program takes a host name as input and prints the ip address. "inet_ntoa" is a library function to print the ip address in the format xx.xx.xx.xx. /*********************************************************** * * Sample gethostbyname program * * building program: * * System v cc -o ptrhost ptrhost.c -linet * * Solaris cc -o ptrhost ptrhost.c -lnsl * * program invocation: * * ptrhost name * * output: * ip address is xx.xx.xx.xx * * ************************************************************/ #include#include #include #include #include #include main(argc,argv) int argc; char **argv; /* alternate *argv[] */ { struct in_addr *ip_ptr; /* point at ip addresses */ /* this is really a ulong */ struct hostent *ptr_hostent; /* point at returned structure */ extern int errno; char *h_ptr; /* point at host name */ h_ptr = *++argv; /* * fill hostent struct */ ptr_hostent = gethostbyname(h_ptr); /* alternate gethostbyname(argv[1]) */ if (ptr_hostent == NULL) { fprintf(stderr,"gethostbyname failed %d\n",errno); exit(-1); } /* * * point at start of ip addresses * */ ip_ptr = (struct in_addr *) *ptr_hostent->h_addr_list; /* * * print ip address in format xx.xx.xx.xx * */ printf("ip address is %s\n",inet_ntoa(*ip_ptr)); } DATE APPROVED: 09/18/95