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]

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]);

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

// gethostbyname() returns NULL pointer if failed.
if (ptr == NULL) {
fprintf(stderr,”gethostbyname() failed\n”);
} 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])));
return 0;



Author: Ali MEZGANI

My name is MEZGANI Ali. I was born back in 1978 in Rabat Morocco. My interests are Debian Linux , programming , science and music.

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s