How to look up domain names and addresses.

To resolve host names and addresses in the domain name system or the local hosts, there are many functions defined as well as the function gethostbyname.

The gethostbyname() is a function that returns a structure of type hostent for the given host name.
Here name is either a host name, or an IPv4 address in standard dot notation.
You can find here an example of using gethostbyname(3).

#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>

struct hostent *ptr;

/* The hostent structure is defined in as follows:
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
}
#define h_addr h_addr_list[0]
*/

int
main(int argc, char **argv)
{

// two arguments are permitted
// the second one is the hostname

if (argc != 2) {
fprintf(stderr,”Usage: %s hostname\n”,argv[0]);
exit(0);
}

ptr = gethostbyname(argv[1]);
int i=0;

// gethostbyname() returns NULL pointer if failed.
if (ptr == NULL) {
fprintf(stderr,”gethostbyname() failed\n”);
exit(1);
} else {

// If the host name, has many translation address so, until there are addresses loop

// we will only use the s_addr field in the in_addr structure
// which records the host address number as an uint32_t

while(ptr -> h_addr_list[i]) {
if ( ptr -> h_addr_list[i] != NULL)
printf(“%s\n”, inet_ntoa( *( struct in_addr*)( ptr -> h_addr_list[i])));
i++;
}
}
return 0;

}

How to look up domain names and addresses.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s