【问题标题】:While trying to ping, java.net.UnknownHostException gets thrown. I do not understand the reason尝试 ping 时,抛出 java.net.UnknownHostException。我不明白原因
【发布时间】:2023-03-21 00:01:02
【问题描述】:

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

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

【问题讨论】:

  • InetAddress.getByName("host") 接受主机名而不是他的协议。例如,如果您的主机是:“localhost:8084/server/abc/page.jsp”这有效

标签: java networking ping unknown-host


【解决方案1】:

问题出在这一行:

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 请求毫无意义。

【讨论】:

  • 这个 localhost 的网络地址可能类似于:http://192.168.43.187:8084/server/index.jsp。客户端如何最初连接到服务器,再次检查它们是否连接到服务器?所以我试图这样做。
  • 客户端如何 ping 地址:http://192.168.43.187:8084/server/index.jsp
  • 1) 名称“localhost”通常绑定到回溯地址,例如`127.0.0.1。如果它绑定到非环回地址,则说明您的网络配置有些问题。 2)请参阅我关于如何从 URL 中提取主机名的答案的更新。 3) 请停止将 URL 称为地址。它是一个资源定位器......不是地址。
【解决方案2】:

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

【讨论】:

  • 那不会给出UnknownHostException
【解决方案3】:

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

【讨论】:

    猜你喜欢
    • 2019-12-21
    • 2021-12-19
    • 1970-01-01
    • 1970-01-01
    • 2015-08-23
    • 1970-01-01
    • 2020-09-15
    • 2015-05-28
    • 1970-01-01
    相关资源
    最近更新 更多