1

我编写了以下代码来尝试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();
      }
}
}

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

4

3 回答 3

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"(通常127.0.0.1)发送 ICMP_PING 请求是毫无意义的。

于 2012-12-10T12:49:53.523 回答
0

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

于 2012-12-10T12:48:10.247 回答
0

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

于 2012-12-10T12:50:42.267 回答