Jake Jake - 14 days ago 5
C Question

Unix - how to get IP address of domain name?

In a C program in UNIX, gethostbyname() can be used to obtain the address of domain like "localhost". How does one convert the result from gethostbyname() to dotted decimal notation.

struct hostent* pHostInfo;
long nHostAddress;

/* get IP address from name */
pHostInfo=gethostbyname("localhost");

if(!pHostInfo){
printf("Could not resolve host name\n");
return 0;
}

/* copy address into long */
memset(&nHostAddress, 0, sizeof(nHostAddress));
memcpy(&nHostAddress,pHostInfo->h_addr,pHostInfo->h_length);


nHostAddress contains the following:

16777243


How do I convert the result so that I can get the output as :

127.0.0.1

Answer

You can convert from a struct in_addr directly to a string using inet_ntoa():

char *address = inet_ntoa(pHostInfo->h_addr);

The value you've got (16777243) looks wrong, though -- that comes out to 1.0.0.27!

Comments