这段代码在 Windows 上运行正常,但 gethostbyaddr 在 Linux 上返回 NULL。
我尝试了很多改变,但都没有成功。
我的/etc/host.conf 有下面这行
订购主机,绑定(bind)
我运行完整代码并传递地址 11.234.456.74, 在 Windows 上,gethostbyaddr 解析地址并且工作正常。 但是在 Linux 上它不解析 ip 地址并返回 NULL。
请帮忙。
#ifdef WIN32
if (init){
WSADATA wsaData;
// Request Winsock version 2.2
if (WSAStartup (MAKEWORD(1, 1), &wsaData) != 0) {
WSACleanup();
exit (EXIT_FAILURE);
}
init = 0;
}
#endif
// Open required socket
p_socket[IP_SOCKET_SOCKET] = socket(AF_INET, server_socket_type, 0);
if ( p_socket[IP_SOCKET_SOCKET] < 0 ) {
#ifdef WIN32
WSACleanup();
#endif
exit (EXIT_FAILURE);
}
destAdrLen = mxGetM(prhs[0]) * mxGetN(prhs[0]) + 1;
destAdr = (char *) mxMalloc(destAdrLen);
if (destAdr == NULL) {
mexErrMsgTxt("mxMalloc(destAdrLen) failed");
}
mxGetString(prhs[0], destAdr, destAdrLen);
destPort = (int) mxGetScalar(prhs[1]);
if (isalpha(destAdr[0])) {
// socket address is a name
hp = gethostbyname(destAdr);
}
else {
// socket address is a number
addr = inet_addr(destAdr);
hp = gethostbyaddr((char *)&addr, 4, AF_INET);
}
最佳答案
该主机似乎没有注册反向 DNS 记录。
$ dig -x 11.234.217.74
; <<>> DiG 9.9.1-P2 <<>> -x 11.234.217.74
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NXDOMAIN, id: 30231
;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 1, ADDITIONAL: 0
;; QUESTION SECTION:
;74.217.234.11.in-addr.arpa. IN PTR
;; AUTHORITY SECTION:
in-addr.arpa. 3599 IN SOA b.in-addr-servers.arpa. nstld.iana.org. 2011026180 1800 900 604800 3600
;; Query time: 1217 msec
因此对gethostbyaddr
的调用将失败。 herror
函数甚至会打印一条消息 Unknown host
。如果您想在这些情况下保留数字 IP,则必须自己编写该代码路径。如果 Windows 做任何其他事情,看看它从哪里获得信息会很有趣。
关于c - gethostbyaddr 在 Windows 上正常,但在 Linux 上返回 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11830514/