Jake Jake - 1 year ago 98
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 */

printf("Could not resolve host name\n");
return 0;

/* copy address into long */
memset(&nHostAddress, 0, sizeof(nHostAddress));

nHostAddress contains the following:


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

Answer Source

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!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download