使用 JAVA 从网络上的 IP 地址获取主机名

Get host name from IP address on network using JAVA

我想找出我网络中所有已连接客户端的信息。我能够找到客户(可以访问)但无法获取有关他的信息。我只需要主机名(计算机名),但下面的代码只打印 IP 地址。我缺少什么?

来源

private void getListOfHost(){
     String subnet="192.168.0";
     int timeout=100;
     for (int i=2;i<15;i++){
         String host=subnet + "." + i;
         try {
            if (InetAddress.getByName(host).isReachable(timeout)) {
                 InetAddress address = InetAddress.getByName(host);
                 System.out.println(host + " is reachable");
                 System.out.println("Canonical host: " + address.getCanonicalHostName());
                 System.out.print("Host name: " + address.getHostName() + "\n");
            }
         }
         catch(Exception e){e.printStackTrace();}
    }
}

输出

192.168.0.6 is reachable
Canonical host: 192.168.0.6
Host name: 192.168.0.6

您没有遗漏代码中的任何内容,但是,错误的来源是被调用系统的安全性manager/firewall.

InetAddress.getCanonicalHostname() 的 Oracle 文档指出:-

Returns:

the fully qualified domain name for this IP address, or if the operation is not allowed by the security check, the textual representation of the IP address.

InetAddress.getHostname() 的 Oracle 文档指出:-

Returns:

the host name for this IP address, or if the operation is not allowed by the security check, the textual representation of the IP address.

解法:-

无论您要查询哪个系统的主机名,只需关闭该系统的防火墙即可。安全经理将始终阻止对网络中其他系统的系统特定查询,因为它被认为不是要共享的信息(不安全)。 你要时刻牢记这件事