Java如何ping IP地址
我使用这部分代码来ping通Java中的ip地址,但只有ping通本地主机才能成功,而对于其他主机,程序会说该主机不可访问。我禁用了防火墙,但是仍然有此问题
public static void main(String[] args) throws UnknownHostException, IOException { String ipAddress = "127.0.0.1";
InetAddress inet = InetAddress.getByName(ipAddress);
System.out.println("Sending Ping Request to " + ipAddress);
System.out.println(inet.isReachable(5000) ? "Host is reachable" : "Host is NOT reachable");
ipAddress = "173.194.32.38";
inet = InetAddress.getByName(ipAddress);
System.out.println("Sending Ping Request to " + ipAddress);
System.out.println(inet.isReachable(5000) ? "Host is reachable" : "Host is NOT reachable");
}
输出为:
Sending Ping Request to 127.0.0.1Host is reachable
Sending Ping Request to 173.194.32.38
Host is NOT reachable
回答:
InetAddress.isReachable()
根据javadoc:
“如果可以获取特权,典型的实现将使用ICMP ECHO REQUEST,否则它将尝试在目标主机的端口7(Echo)上建立TCP连接。”
选项1(ICMP)通常需要管理(root)
权限。
以上是 Java如何ping IP地址 的全部内容, 来源链接: utcz.com/qa/434302.html