执行ping要加上参数,windows如果不指定默认ping 4次但是linux则一直ping,这个坑浪费了不少时间
public static StringBuilder ping(String hostIp){
BufferedReader br = null;StringBuilder sb=new StringBuilder();
try {
String osName = System.getProperty("os.name");//获取操作系统类型
String command = "";
if(osName.contains("Linux")){
command = "ping -c 3 -i 1 "+hostIp; //ping参数 ping3次
}else{
command = "ping -n 3 -w 1 "+hostIp;
}
Process p = Runtime.getRuntime().exec(command);
br = new BufferedReader(new InputStreamReader(p.getInputStream(),"gbk"));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return sb;
}
/**
* 根据ping返回信息判断有没有ping成功
* @param line ping返回的结果
* @return ping成功返回true
* 失败返回false
*/
public static boolean pingAcce(String hostIp){
boolean res=false;
StringBuilder line = ping(hostIp);
Pattern pattern =Pattern.compile("(\\d+ms)(\\s+)(TTL=\\d+)|(ttl=\\d+)",Pattern.CASE_INSENSITIVE);
Matcher matcher =pattern.matcher(line);
while(matcher.find()){
res=true;
}
return res;
}