|
DNS - The Domain Name Service
The second network database service is that which converts host and domain
names into IP numbers and vice versa. This is the domain name service, usually
implemented by the BIND (Berkeley Internet Name Domain) software. The
information here concerns version 4.9 of this software.
This is perhaps the most important function form hostname lookup.
´gethostbyname()' gets its
information either from files, NIS or DNS. Its behaviour is configured by the
files mentioned above, See section
DNS - The Domain Name Service.
It is used to look up the IP address of a named host (including domain name if
DNS is used). On the configurable systems described above, the full list of
servers is queried until a reply is obtained. The order in which the different
services are queried is important here since DNS returns a fully qualified
name (host name plus domain name) whereas NIS and the
´/etc/hosts' file database return
only a hostname.
gethostbyname returns data in the form of a pointer to a static data
structure. The syntax is
#include <netdb.h>
struct hostent *hp;
hp =
gethostbyname("myhost.domain.country")
The resulting structure varies on different implementations of UNIX, but
the ´old BSD standard' is of the form:
struct hostent
{
char *h_name; /* official name of
host */
char **h_aliases; /* alias list
*/
int h_addrtype; /* host address
type */
int h_length; /* length of
address */
char **h_addr_list; /* list of
addresses from name server */
};
#define h_addr h_addr_list[0] /* address,
for backward compatiblity */
The structure contains a list of addresses and or aliases from the
nameserver. The interesting quantity is usually extracted by means of the macro
´h_addr' whcih gives the first
value in the address list, though officially one should examine the whole list
now.
This value is a pointer which can be converted into a text form by the
following hideous type transformation:
#include
<sys/types.h>
#include
<sys/socket.h>
#include
<netinet/in.h>
struct sockaddr_in sin;
cin.sin_addr.s_addr = ((struct in_addr
*)(hp->h_addr))->s_addr;
printf("IP address =
%s\n",inet_ntoa(cin.sin_addr));
See the client program in the first section of this chapter for an example
of its use.
|