IP-to-Hostname Translation

Many companies and organizations host an FTP site, a mail server, and a

Web server on the same machine. In such cases, the hostnames

ftp.ripoff.org, mail.ripoff.org, and www.ripoff.org are usually mapped

to a single IP address. Similarly, a company may map different IP

addresses (one address per server, say) to a single hostname. Thus, we

can conclude that every IP address corresponds to zero or more

hostnames and every hostname corresponds to zero or more IP addresses.

Many-to-Many Mapping

The struct hostent declared

handles this many-to-many IP-to- hostname mapping: struct hostent { char *h_name; char **h_aliases; int h_addrtype; int h_length; char **h_addr_list; }; Although a host may have several names, only one, known as its "canonical name," is official. The canonical name is stored in h_name. The rest of the host's names are called "aliases," and are stored in h_aliases as a list of strings. The final element of h_aliases is a NULL pointer, indicating the end of the list. The field h_addrtype stores the address's type. Under the IPv4 protocol, its value is always AF_INET. The h_length field contains the address's size in bytes. It's equal to sizeof(in_addr). The final field, h_addr_list, is a pointer to a list of generic pointers. When the h_addrtype value is AF_INET, these generic pointers actually point to in_addr structs. Here again a NULL pointer indicates the end of the list. Translation Functions The library functions gethostbyname() and gethostbyaddr() translate a hostname to its IP addresses and vice versa. gethostbyname() has the following prototype: struct hostent *gethostbyname(const char *name); The function takes a hostname and returns a pointer to a statically allocated hostent struct. Since each call to gethostbyname() will overwrite it, you should copy the returned struct to a private hostent object. gethostbyaddr() retrieves a list of hostnames associated with a certain IP address. It has the following prototype: struct hostent *gethostbyaddr(const void *addr, size_t addrlen, int type); For our purposes, the first argument should always point to an in_addr struct, the second argument should equal sizeof(in_addr), and the third argument should be AF_INET. The function fills a hostent struct with a list of hostnames and returns its address. In case of a failure, these functions assign an error code to the global variable h_errno. The herror() function, which behaves very much like perror() (see my earlier newsletter, "Error Handling," at http://www.itworld.com/nl/lnx_tip/03092001 for more), displays a verbal description of the error.
What’s wrong? The new clean desk test
Join the discussion
Be the first to comment on this article. Our Commenting Policies