Thursday, November 8, 2012

gethostbyname example in C


gethostbyname() function will return the host details such as hostname, aliase names of the host,type of address, and length of host address of the given hostname.

This function will return the hostent (host entry) structure which contain the all the above details. h_addr_list[0]  field of “hostent” structure will contain struct in_addr equivalent of the host address.


Sysntax

struct hostent *gethostbyname(const char *name);

Here name is any valid hostname  (or) IPV4 address in standard dot notation (or) IPV6  address in colon or dot notation


Here is the simple C Program in Linux that illustrates the gethostbyname() function.

hostinfobyname.c
-->


#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>  //for gethostname()
#include<netinet/in.h>
#include<arpa/inet.h> // for inet_ntoa()
#include<netdb.h> // for hostent structure, gethostbyname()
#include<string.h>

int main(int argc,char *argv[])
{
 char *hname,**aliases,**address;
 struct hostent *hostinfo;
 struct in_addr ipadd;

 if(argc == 1) {
  char myname[256];
  gethostname(myname,255);
  hname = myname;
  //printf("host name %s",hname);
 }
 else {
  hname = argv[1];
 }
 
 
 hostinfo = gethostbyname(hname);
 if(!hostinfo) {
  fprintf(stderr, "can not get info for the HOST %s\n",hname);
  exit(1);
 }
 printf("Result for Host %s \n",hname); 
 printf("Host name: %s \n",hostinfo->h_name);
 printf("Aliases: ");
 aliases = hostinfo->h_aliases;
 while(*aliases)  {
  printf("%s ",*aliases);
  aliases++;  
 }
 printf("\n");
 
 if(hostinfo->h_addrtype != AF_INET) {
  fprintf(stderr," Not a IP host \n");
  exit(1); 
 }
 printf("Type: %s\n",hostinfo->h_addrtype==AF_INET? "AF_INET" : "AF_INET6");
 
 printf("Length of addrs in bytes : %d \n",hostinfo->h_length);  
 
 printf("Address list: ");
 address = hostinfo->h_addr_list;
 while(*(address)) {
  printf("%s ",inet_ntoa(*(struct in_addr *)*address));
  address++;
 } 
 ipadd=*(struct in_addr *)hostinfo->h_addr_list[0]; 
 printf("\n");
 printf("IP Address: %s\n",inet_ntoa(ipadd));
  
return 0;
}



Output:
$gcc -o hostinfo hostinfobyname.c
$./hostinfo

Result for Host developersFactory-LAP08 

Host name: developersFactory-LAP08 
Aliases: 
Type: AF_INET 
Length of addrs in bytes : 4 
Address list: 127.0.1.1 
IP Address: 127.0.1.1 


1 comment: