Alex
Alex

Reputation: 3381

gethostbyaddr return NULL even with a valid IP

I am trying connect on a server using just the IP, but I got the error 11004 when I used gethostbyaddr function, I used the function like that:

WSADATA wsaData;
DWORD dwError;
struct hostent *remoteHost;
char host_addr[] = "127.0.0.1"; //or any other IP
struct in_addr addr = { 0 };

addr.s_addr = inet_addr(host_addr);
if (addr.s_addr == INADDR_NONE) {
  printf("The IPv4 address entered must be a legal address\n");
  return 1;
} else
  remoteHost = gethostbyaddr((char *) &addr, 4, AF_INET);


if (remoteHost == NULL) {
   dwError = WSAGetLastError();
   if (dwError != 0)
      printf("error: %d", dwError)
}

I got this error: 11004 by WSAGetLastError function:

WSANO_DATA
11004



Valid name, no data record of requested type.

The requested name is valid and was found in the database, but it does not have the correct
associated data being resolved for. The usual example for this is a host name-to-address 
translation attempt (using gethostbyname or WSAAsyncGetHostByName) which uses the DNS 
(Domain Name Server). An MX record is returned but no A record—indicating the host itself 
exists, but is not directly reachable.

PS: My code works ok when I use gethostbyname.

Upvotes: 0

Views: 2885

Answers (1)

Angus Comber
Angus Comber

Reputation: 9708

Did you forget to initialise winsock

#include <stdio.h>
#include <winsock2.h>

#pragma comment(lib, "Ws2_32.lib")

int main() {
   WSADATA wsaData;
   // Initialize Winsock
   int wret = WSAStartup(MAKEWORD(2,2), &wsaData);
   if (wret != 0) {
      printf("WSAStartup failed: %d\n", wret);
      return 1;
   }

   DWORD dwError;
   struct hostent *remoteHost;
   char host_addr[] = "127.0.0.1"; //or any other IP
   struct in_addr addr = { 0 };

   addr.s_addr = inet_addr(host_addr);
   if (addr.s_addr == INADDR_NONE) {
      printf("The IPv4 address entered must be a legal address\n");
      return 1;
   } else
      remoteHost = gethostbyaddr((char *) &addr, 4, AF_INET);


   if (remoteHost == NULL) {
      dwError = WSAGetLastError();
      if (dwError != 0)
         printf("error: %d", dwError);
   }
   else {
      printf("Hostname: %s\n", remoteHost->h_name);
   }

   WSACleanup();

   return 0;
}

This code above works for me for 127.0.0.1 and for some remote hosts on my LAN. But interestingly, for my router, which presumably has no hostname I get the same 11004 winsock error.

And in that case.

struct hostent* hostbyname = gethostbyname(host_addr);

if (hostbyname == NULL) {
   dwError = WSAGetLastError();
   if (dwError != 0)
      printf("error: %d", dwError);
}
else {
   printf("Hostname: %s\n", hostbyname->h_name);
}

doesn't return a hostname either, and results in the same error - 11004.

So puzzled by your experience.

Upvotes: 1

Related Questions