我正在使用这部分代码在java中ping一个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");
}
输出为:
向127.0.0.1发送Ping请求
主机可访问
向173.194.32.38发送Ping请求
主机无法访问
发布于 2020-08-21 17:21:55
我更喜欢这样:
/**
*
* @param host
* @return true means ping success,false means ping fail.
* @throws IOException
* @throws InterruptedException
*/
private static boolean ping(String host) throws IOException, InterruptedException {
boolean isWindows = System.getProperty("os.name").toLowerCase().contains("win");
ProcessBuilder processBuilder = new ProcessBuilder("ping", isWindows? "-n" : "-c", "1", host);
Process proc = processBuilder.start();
return proc.waitFor(200, TimeUnit.MILLISECONDS);
}
这种方式可以将阻塞时间限制在特定的时间内,例如200ms。
它在MacOS、Android和Windows上运行良好,应该在jdk1.8中使用。
这个想法来自Mohammad Banisaeid,但我无可奉告。(你必须有50个声誉才能评论)
https://stackoverflow.com/questions/11506321
复制相似问题