View Antoni Milton's profile on LinkedIn

Thursday, March 11, 2010

How to convert domain name to IPAddress in C++?

Using the gethostbyname() system call we can get the IPAddress from domain name. Below given example program , convert the domain name to IPAddress and print the IPAddress in "." format ( xxx.xxx.xxx.xxx. )

#include "stdio.h"
#include "sys/types.h"
#include "sys/socket.h"
#include "netdb.h"
#include "netinet/in.h"
#include "arpa/inet.h"

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

struct hostent *host;
struct in_addr addr;
if( argc != 2 )
{
printf("usage: ./a.out "domainname" ");
return 0;
}


if ((host = gethostbyname(argv[1])) == NULL) {
printf("error resolving hostname..\n");
return -1;
}

addr.s_addr = *(u_long *) host->h_addr_list[0];
printf("IP: %s\n", inet_ntoa( addr ) );
return 0;
}

No comments: