话不多说直接上代码
class text{
public static void main(String[] args) {
boolean isSuccess = ping("192.168.1.218");
}
private boolean ping(String ip) {
log.info("ping ip:" + ip);
//os:1-windows、2-linux
int os = 2;
BufferedReader in = null;
Runtime r = Runtime.getRuntime();
String pingCommand = "";
String pingCommand1 = "ping " + ip + " -n 5 -w 10";
String pingCommand2 = "ping " + ip + " -c 5 -W 10";
if (os == 1) {
pingCommand = pingCommand1;
} else {
pingCommand = pingCommand2;
}
try {
Process p = r.exec(pingCommand);
if (p == null) {
return false;
}
in = new BufferedReader(new InputStreamReader(p.getInputStream()));
int connectedCount = 0;
String line = null;
while ((line = in.readLine()) != null) {
log.info("line:" + line);
connectedCount += getCheckResult(line);
}
log.info("count:" + connectedCount);
return (connectedCount >= 1);
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private int getCheckResult(String line) {
if ((line.contains("ttl=") || line.contains("TTL=")) && line.contains("ms")) {
return 1;
}
return 0;
}
}
有帮助的话记得点赞收藏