我在 Stack Overflow 上寻找如何在 Java 中进行 IP 查找,但答案与我已经在做的事情相匹配,并且不能解决我的问题。
这是我的代码:
public void printHostname( String ip ) {
System.out.println( InetAddresses.forString( ip ).getCanonicalHostName( ) );
}
InetAddresses
只是来自 guava 库的实用程序类,用于获取InetAdress
.
问题:此代码在某些 IP 地址上按预期工作,而在其他一些 IP 地址上则不行。
一个工作示例
例如,对于 IP 157.55.39.29,输出为:
msnbot-157-55-39-29.search.msn.com
根据 Linuxhost
命令,这个结果似乎是正确的:
> 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
绕过内部异常获取变量值吗?