【问题标题】:gethostbyaddr is OK on Windows but returns NULL on Linuxgethostbyaddr 在 Windows 上可以,但在 Linux 上返回 NULL
【发布时间】:2012-08-06 14:41:45
【问题描述】:

这段代码在 Windows 上运行正常,但在 Linux 上 gethostbyaddr 返回 NULL。

我尝试了很多更改,但都没有成功。

我的 /etc/host.conf 有以下行

订购主机,绑定

我运行完整代码并传递地址 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);
}

【问题讨论】:

  • 11.234.456.74 不是有效的 IPv4 地址,这可能是原因。 h_errno 有什么价值?
  • 感谢丹尼尔的评论。这是一个错字。我的意思是说 11.234.217.74 这是一个有效的地址。在 Windows 上运行代码时,它可以正确解析。但是在 Linux 上运行时失败。 gethostbyaddr 在 Linux 上返回 NULL。
  • 您为 destAdr 分配了内存,但它似乎是空的……至少在您的示例代码中。
  • @shinkou 是对的。您为destAdr 分配了内存,但在使用它之前没有将IP 字符串复制到其中,因此它包含垃圾。这段代码也不可能在 Windows 上运行。
  • 我添加了几行缺失的代码。 destAdr 和 destPort 从 matlab 中的调用函数传递给代码。该代码在 Windows 中运行良好。如果我在 Lunix 中检查指针 hp 。运行后为0。

标签: c networking network-programming


【解决方案1】:

该主机似乎没有注册反向 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 做了其他任何事情,看看它从哪里获取信息会很有趣。

【讨论】:

  • 感谢您的回复。我已经用很少的已知地址(如 212.58.226.75)尝试了这段代码。看来它正在工作。然后用我的一些工作地址试了一下。它失败了。这告诉我,我的工作地址的 DNS 无法正常工作。对于 Windows。这很奇怪。我不知道为什么在 Windows 中 gethostbyaddress 没有返回 NULL,尽管 DNS 在内部没有工作。难道是windows和linux使用不同的DNS程序?
  • 只是猜测,但可能是 Windows 使用 WINS 解析名称。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-25
  • 2022-08-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多