pointer
pointer

Reputation: 307

Linux networking (gethostbyaddr)

I am trying to get host information about the host with IP address 89.249.207.231. I know that it exists, because when I type the IP address in my browser's url field it finds the page. Here is my code in C.

#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <errno.h>

int main()
{
    struct in_addr addr;
    inet_aton("89.249.207.231", &addr);
    struct hostent* esu = gethostbyaddr((const char*)&addr),sizeof(addr), AF_INET);
    printf("%s\n", esu->h_name);
    return 0;
}

When I compile and run it, it gives "Segmentation fault". I can not understand the problem with my code.

Any hints and suggestions would be appreciated.

Thanks!

Upvotes: 0

Views: 9679

Answers (1)

Manos
Manos

Reputation: 2186

Even if the host exists, you may not be able to extract its hostname.

For example, the following code, without the deprecated functions that you use gives the result host=google-public-dns-a.google.com whereas with your host address gives could not resolve hostname.

The reason of your segfault, is that esu is NULL, because the function could not resolve a hostname by the given IP.

Here is the code:

#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>

int main()
{
    struct sockaddr_in sa;    /* input */
    socklen_t len;         /* input */
    char hbuf[NI_MAXHOST];
    
    memset(&sa, 0, sizeof(struct sockaddr_in));
    
    /* For IPv4*/
    sa.sin_family = AF_INET;
    sa.sin_addr.s_addr = inet_addr("8.8.8.8");
    len = sizeof(struct sockaddr_in);
    
    if (getnameinfo((struct sockaddr *) &sa, len, hbuf, sizeof(hbuf), 
        NULL, 0, NI_NAMEREQD)) {
        printf("could not resolve hostname\n");
    }
    else {
        printf("host=%s\n", hbuf);
    }
    
    return 0;                                                  
}

Upvotes: 3

Related Questions