我在 Stack Overflow 上寻找如何在 Java 中进行 IP 查找的方法,但答案与我已经在做的事情相同,并没有解决我的问题。
这是我的代码:
public void printHostname( String ip ) {
System.out.println( InetAddresses.forString( ip ).getCanonicalHostName( ) );
}
InetAddresses
是guava库中的一个实用类,用于获取InetAddress
。
问题是:该代码对某些IP地址有效,对另一些则无效。
一个有效示例
例如,对于IP 157.55.39.29,输出结果为:
msnbot-157-55-39-29.search.msn.com
根据 Linux host
命令,这个结果似乎是正确的:
> host 157.55.39.29
29.39.55.157.in-addr.arpa domain name pointer msnbot-157-55-39-29.search.msn.com.
一个不起作用的示例
对于IP地址123.125.71.75,host
命令返回:
> host 123.125.71.75
75.71.125.123.in-addr.arpa domain name pointer baiduspider-123-125-71-75.crawl.baidu.com.
但是我的Java代码的输出结果是:
123.125.71.75
期望的输出应该是
baiduspider-123-125-71-75.crawl.baidu.com
getCanonicalHostName方法的Javadoc说:
返回值:
此IP地址的完全限定域名,如果该操作未经安全检查允许,则返回IP地址的文本表示形式。
但我相信这不是安全检查的问题...或者我不理解哪里出了问题。
您有什么建议来解释这种行为吗?您有没有解决方法?
编辑 #1
在寻找解决方案时,我尝试逐步调试JDK中的实现:
// 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);
在这段代码中,变量host
包含正确的值,但是调用getAllByName0
的最后一个语句抛出了一个UnknownHostException
异常,该异常通过返回所请求的IP地址来处理。异常由内部方法getAddressesFromNameService
抛出,错误信息如下:
"java.net.UnknownHostException: baiduspider-123-125-71-75.crawl.baidu.com"
我不知道为什么。
我可以绕过内部异常获取host
变量的值吗?