当我尝试使用网络IP ping我自己的电脑时,我得到java.net.UnknownHostException的原因是什么?

时间:2012-12-14 11:11:13

标签: java tomcat web-applications unknown-host

我尝试使用以下代码行ping服务器,这是我自己的PC:

InetAddress.getByName(serverResourceLocator).isReachable(5000)

// where serverResourceLocator is  192.168.43.187/server/ping?ip=Adarsh-PC/192.168.43.187&time=1355482205301

此处192.168.43.187是我的电脑的网络IP,我从命令ipconfig

了解到的
Wireless LAN adapter Wireless Network Connection:

Connection-specific DNS Suffix  . :
Link-local IPv6 Address . . . . . : fe80::f5be:cfa7:5c38:efff%14
IPv4 Address. . . . . . . . . . . : 192.168.43.187
Subnet Mask . . . . . . . . . . . : 255.255.255.0
Default Gateway . . . . . . . . . : 192.168.43.1

在我的电脑上,我正在运行tomcat作为服务器。为什么我会收到UnknownHostException


java.net.UnknownHostException: 192.168.43.187/server/ping?ip=Adarsh-PC/192.168.43.187&time=1355482205301
at java.net.InetAddress.getAllByName0(InetAddress.java:1140)
at java.net.InetAddress.getAllByName0(InetAddress.java:1109)
at java.net.InetAddress.getAllByName(InetAddress.java:1072)
at java.net.InetAddress.getByName(InetAddress.java:969)
at internet.CommunicationWithServer.PingTheServer.ping(PingTheServer.java:35)
at internet.CommunicationWithServer.PingTheServer.access$000(PingTheServer.java:11)
at internet.CommunicationWithServer.PingTheServer$1.run(PingTheServer.java:21)
at java.lang.Thread.run(Thread.java:619)

2 个答案:

答案 0 :(得分:3)

.getByName() method需要主机名,而不是您提供的(半)URL。引用JavaDoc:

  

主机名可以是计算机名称,例如“java.sun.com”,也可以是 IP地址的文本表示。如果提供了文字IP地址,则仅检查地址格式的有效性。

(我的重点)。

试试InetAddress.getByName( "192.168.43.187" ).isReachable(5000),你会没事的。

我发现你编写了一个可以ping IP的servlet。如果是这样的话。通过HTTP响应返回延迟,然后你应该使用eg。 HttpClient包以编程方式获取该响应;在SO上有几个线程来完成它。

干杯,

答案 1 :(得分:1)

serverResourceLocator更像是一个网址,而InetAddress.getByName需要一个主机名:

尝试

InetAddress.getByName("192.168.43.187").isReachable(5000)