• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 278
  • Last Modified:

Finding IP Address without knowing the Hostname

If I cannot get the hostname from gethostname, is there another way to get the IP address that is independent of knowing the hostname?
  • 2
1 Solution
If you cannot determine the hostname, IP isn't configured correctly (->'gethostname()'). But as every host has a loopback IF (i.e. IP, you can use this one in a call to 'gethostbyaddr()' and extract the other addresses form the 'h_addr_list' member of the 'HOSTENT' struct returned by this call.
paulcaAuthor Commented:
The code I'm using is which gives me an error:

pHost = gethostbyaddr("", 4, PF_INET);

for(j=0;j<pHost->h_length;j++) {

                        if(j>0) {
                              strcat(addrStrings, ".");
                        sprintf(buf, "%u", (unsigned int)((unsigned char*)pHost->h_addr_list[i])[j]);
                        strcat(addrStrings, buf);
                        printf (addrStrings);
Ooops, it seems that the comment I posted some hours ago is gone...

So, again:

The addresses are stored as DWORDs in network byte order - use sth like

char    *BinIP2StrIP    (   long    lnIP)
    static char     s_acStrIP   [   16];

    PUCHAR          puc =   ( unsigned char *) &lnIP;
    unsigned int    aun [   4];

    for (   int i = 0;  i < 4;  aun [   i++]    =   *puc++);

    sprintf (   s_acStrIP,
                aun [   0],
                aun [   1],
                aun [   2],
                aun [   3]

    return  (   s_acStrIP);

for(j=0;dwIP = pHost->h_addr_list [j];j++)
 printf ( "%s", BinIP2StrIP ( dwIP));

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now