项目需求,判定节点是否可达!
public static final boolean isNodeReachable(String hostname) {
try {
InetAddress address = InetAddress.getByName(hostname);
if (address.isReachable(3000)) {
return true;
} else {
return false;
}
} catch (Exception e) {
System.out.println(hostname + "网络不可达!");
e.printStackTrace();
return false;
}
}
之前测试过该方法,没有发现问题。今天发现该方法一直返回false,实际上通过ping命令是可以ping通的。
曲线救国,只好通过Runtime执行ping命令了
public static final boolean isNodeReachable(String hostname) {
try {
return 0==Runtime.getRuntime().exec("ping -c 1 "+hostname).waitFor();
} catch (InterruptedException | IOException e) {
e.printStackTrace();
return false;
}
}