InetAddress.getCanonicalHostName() returns IP instead of Hostname

前端 未结 2 828
醉梦人生
醉梦人生 2020-12-06 16:57

I looked for how to do IP lookup in Java on Stack Overflow but the answers match what I am already doing and do not resolve my problem.

Here is my code:



        
2条回答
  •  不知归路
    2020-12-06 17:19

    I did not dig a lot into this so I don't know why it is happening, but some online tools (like this one) that checks the health of DNS servers indicates that they have some issues which may or may not be related.

    As @jah said, Java tries to double check to see if the hostname has the ip it said it has. The exception is thrown on the native code while trying to do that. In fact, in my case, trying to verify on the command line, the nslookup fails to get the ip from the name, which indicates some configuration preventing this on the DNS Server (maybe on purpose? I'm no expert in DNS either).

    When it works:

    $ nslookup msnbot-157-55-39-29.search.msn.com
    Server:         192.168.1.1
    Address:        192.168.1.1#53
    
    Non-authoritative answer:
    Name:   msnbot-157-55-39-29.search.msn.com
    Address: 157.55.39.29
    

    When it doesnt work:

    $ nslookup baiduspider-123-125-71-75.crawl.baidu.com
    Server:         192.168.1.1
    Address:        192.168.1.1#53
    
    ** server can't find baiduspider-123-125-71-75.crawl.baidu.com: NXDOMAIN
    

    When it works:

    $ getent hosts msnbot-157-55-39-29.search.msn.com
    157.55.39.29    msnbot-157-55-39-29.search.msn.com
    

    When it doesn't:

    $ getent hosts baiduspider-123-125-71-75.crawl.baidu.com
    $
    

    As an alternative, you can use a DNS Service Provider for JNDI. The documentation has an example, but I'll leave a working snippet for you to test:

    String[] octets = "123.125.71.75".split("\\.");
    String host = String.join(".", octets[3], octets[2], octets[1], octets[0], "in-addr.arpa");
    
    Properties props = new Properties();
    props.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
    DirContext dirContext = new InitialDirContext(props);
    
    Attributes attrs = dirContext.getAttributes(host, new String[] {"PTR"});
    
    System.out.println(attrs.get("PTR").get());
    

提交回复
热议问题