Networking 211
From /usr/include/netdb.h
/ Description of database entry for a single host. /
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 compatibility. /
};
The following code demonstrates the use of the gethostbyname() function.
host_lookup.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include "hacking.h"
int main(int argc, char argv[]) {
struct hostent host_info;
struct in_addr *address;
if(argc < 2) {
printf("Usage: %s
exit(1);
}
host_info = gethostbyname(argv[1]);
if(host_info == NULL) {
printf("Couldn't lookup %s\n", argv[1]);
} else {
address = (struct in_addr ) (host_info->h_addr);
printf("%s has address %s\n", argv[1], inet_ntoa(address));
}
}
This program accepts a hostname as its only argument and prints out the
IP address. The gethostbyname() function returns a pointer to a hostent struc-
ture, which contains the IP address in element h_addr. A pointer to this element
is typecast into an in_addr pointer, which is later dereferenced for the call to
inet_ntoa(), which expects a in_addr structure as its argument. Sample program
output is shown on the following page.