gethostbyaddr is OK on Windows but returns NULL on

2020-04-28 02:54发布

问题:

This piece of code works OK on windows, but gethostbyaddr returns NULL on Linux.

I have tried so many changes, but without any success.

My /etc/host.conf has the following line

order hosts,bind

I run the full code and pass address 11.234.456.74, On windows gethostbyaddr resolves the address and works fine. However on Linux it does not resolve the ip address and returns NULL.

Please help.

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

回答1:

That host doesn't appear to have a reverse dns record registered.

$ 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

So the call to gethostbyaddr will fail. The herror function will even print a message of Unknown host. If you want to keep the numeric IP in those cases, you'll have to write that code path yourself. If Windows does anything else, it would be interesting to see where it got its information from.