Search code examples
cnetwork-programminghostent

Why does this hostent cause a segfault?


struct hostent *hostName;

struct in_addr ipv4addr;

inet_pton(AF_INET, inet_ntoa(client.sin_addr), &ipv4addr);

hostName = gethostbyaddr(&ipv4addr, sizeof(ipv4addr), AF_INET);

printf("Host name: %s\n", hostName->h_name);

It segfaults on the last line. I looked up proper use of hostent, and the msdn docs show it being used EXACTLY like this. What would cause the segfault?


Solution

  • The gethostbyaddr() function returns NULL in the case of an error, and I don't see you checking for that in your code. Attempting to dereference a NULL pointer would cause a segfault.

    You need something like:

    if (hostName == NULL) {
      printf("There was an error!\n");
      exit(1);
    }
    

    You may be able to use the herror() function to print out the actual error encountered by the resolver (although the man page indicates that herror() is obsolete).