java代码
public boolean ping(String ipAddress, int pingTimes, int timeOut) {
BufferedReader in = null;
String pingCommand;
Runtime r = Runtime.getRuntime();
String osName = System.getProperty("os.name");
if(osName.contains("Windows")){
pingCommand = "ping " + ipAddress + " -n " + pingTimes + " -w " + timeOut;
}else{
pingCommand = "ping " + " -c " + "4" + " -w " + "2 " + ipAddress;
}
try {
Process p = r.exec(pingCommand);
if (p == null) {
return false;
}
in = new BufferedReader(new InputStreamReader(p.getInputStream()));
int connectedCount = 0;
String line;
while ((line = in.readLine()) != null) {
connectedCount += getCheckResult(line,osName);
}
return connectedCount >= 2 ? true : false;
} catch (Exception ex) {
ex.printStackTrace();
return false;
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static int getCheckResult(String line,String osName) {
if(osName.contains("Windows")){
if(line.contains("TTL=")){
return 1;
}
}else{
if(line.contains("ttl=")){
return 1;
}
}
return 0;
}