我正在尝试使用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
时,我的代码正常。
答案 0 :(得分:1)
你有没有忘记初始化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。
对你的经历感到困惑。