0
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?

porque_no_les_deux
  • 479
  • 1
  • 6
  • 18
  • Maybe gethostbyaddre resturns NULL and dereferencing NULL causes a segfault; or hostName->h_name is NULL and then printf()'ing NULL segfaults. –  Apr 25 '12 at 20:43

1 Answers1

1

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).

larsks
  • 277,717
  • 41
  • 399
  • 399