3

I'm trying to write a simple java program that will return the dns names of ip addresses which I do using the following code:

InetAddress host = InetAddress.getByName(ip);
String dnsName = host.getHostName();

When a dns name is registered getHostName() returns this name and when there is no existent dns name the ip address is returned.

For many addresses the above code doesn't return any while the nslookup command returns.

For example, for the address 82.117.193.169 nslookup returns peer-AS31042.sbb.rs while getHostName() returns only the address. This doesn't happen for all the addresses but for a large number of cases.

4

2 回答 2

1

默认情况下,您的计算机可能未配置为使用 DNS,即使它是按需可用的。

我会尝试

ping 82.117.193.169

并查看它是否将 IP 地址解析为主机名。

于 2012-09-03T18:14:34.263 回答
1

It is due to the "A" record check - Java wants that IP number you're looking up, was listed there. They call it "XXX" and I understand why:

private static String getHostFromNameService(InetAddress addr, boolean check) {
String host = null;
for (NameService nameService : nameServices) {
    try {
        // first lookup the hostname
        host = nameService.getHostByAddr(addr.getAddress());

        /* check to see if calling code is allowed to know
         * the hostname for this IP address, ie, connect to the host
         */
        if (check) {
            SecurityManager sec = System.getSecurityManager();
            if (sec != null) {
                sec.checkConnect(host, -1);
            }
        }

        /* now get all the IP addresses for this hostname,
         * and make sure one of them matches the original IP
         * address. We do this to try and prevent spoofing.
         */

        InetAddress[] arr = InetAddress.getAllByName0(host, check);
        boolean ok = false;

        if(arr != null) {
            for(int i = 0; !ok && i < arr.length; i++) {
                ok = addr.equals(arr[i]);
            }
        }

        //XXX: if it looks a spoof just return the address?
        if (!ok) {
            host = addr.getHostAddress();
            return host;
        }

        break;
于 2017-04-04T03:57:35.487 回答