在尝试ping时,会抛出java.net.UnknownHostException。我不明白原因

时间:2012-12-10 12:42:16

标签: java networking ping unknown-host

我编写了以下代码来尝试ping。但是当我运行它时,会抛出以下异常:

java.net.UnknownHostException: http://localhost:8084/server/index.jsp
    at java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method)
    at java.net.InetAddress$1.lookupAllHostAddr(Unknown Source)
    at java.net.InetAddress.getAddressFromNameService(Unknown Source)
    at java.net.InetAddress.getAllByName0(Unknown Source)
    at java.net.InetAddress.getAllByName0(Unknown Source)
    at java.net.InetAddress.getAllByName(Unknown Source)
    at java.net.InetAddress.getByName(Unknown Source)
    at Tester.main(Tester.java:10)

import java.net.InetAddress;

class Tester {
public static void main(String args[]) {
    try {
      InetAddress address = InetAddress.getByName("http://localhost:8084/server/index.jsp");
      boolean isReachable = address.isReachable(2000);
      if(isReachable)
        System.out.println("The address is reachable");
      else
        System.out.println("The address is not reachable");

    } catch(Exception exc) {
       exc.printStackTrace();
      }
}
}

为什么会这样?服务器正在运行,页面在Web浏览器中正常打开。

3 个答案:

答案 0 :(得分:5)

问题出在这一行:

InetAddress address = InetAddress.getByName(
        "http://localhost:8084/server/index.jsp");

InetAddress.getByName(String)方法需要主机名。你给它一个URL字符串。该地址的主机名组件为"localhost"

如果要“ping”与URL关联的主机,则需要解析URL并解析主机名组件,如下所示:

String hostname = new URL(str).getHost();

但是您需要处理URL格式错误的情况,或者没有主机名组件的情况。


我想你实际试图测试其他主机名,因为向"localhost"发送ICMP_PING请求(通常为127.0.0.1)是没有意义的。

答案 1 :(得分:0)

因为firewall后面的域阻止了ping请求

答案 2 :(得分:0)

getByName将主机名或IP地址作为参数,而不是e URL。