我正在尝试仅使用IP在服务器上进行连接,但是当我使用error 11004函数时得到了gethostbyaddr,我使用了如下函数:

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


我收到此错误:11004通过WSAGetLastError函数:

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:使用gethostbyname时,我的代码可以正常工作。

最佳答案

你忘了初始化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;
}


上面的代码对我来说适用于127.0.0.1和局域网上的某些远程主机。但是有趣的是,对于我的路由器(大概没有主机名),我遇到了相同的11004 winsock错误。

在那种情况下。

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);
}


也不返回主机名,并导致相同的错误-11004。

令您感到困惑。

关于c - 即使具有有效的IP,gethostbyaddr仍返回NULL,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27377245/

10-13 02:57