package com.sitech.utils.ssh;import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;/**
 * 判断ip是否能ping通
 * 
 * @author lipp
 */
public class SshPingIp { /**
 * ping所有的机器
 * 
 * @param ip
 * @return
 */
public static boolean pingOtherServer(String ip) {
boolean flag = pingLinuxServer(ip);
if (!flag) {
flag = pingWindowsServer(ip);
}
return flag;
} public static boolean pingLinuxServer(String ip) {
/**
 * 在windows下和linux下的ping命令格式不相同需要注意
 */
String shellPingCmd = "ping " + ip + " -c 2";
Runtime rr = Runtime.getRuntime();
InputStream in = null;
try {
in = rr.exec(shellPingCmd).getInputStream();
if (in != null) {
byte[] tmp = new byte[1024];
for (int j = 0; j < 5; j++) {
while (true) {
int i = in.read(tmp, 0, 1024);
if (i < 0) {
break;
}
String line = new String(tmp, 0, i);
if (line != null && !"".equals(line)) {
if (line.contains("bytes") && line.contains("time")
&& (line.contains("ttl") || line.contains("TTL"))) {
return true;
}
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return false;
} public static boolean pingWindowsServer(String ip) {
/**
 * 在windows下和linux下的ping命令格式不相同需要注意
 */
String shellPingCmd = "ping " + ip;
Runtime rr = Runtime.getRuntime();
InputStream in = null;
try {
in = rr.exec(shellPingCmd).getInputStream();
byte[] tmp = new byte[1024];
for (int j = 0; j < 5; j++) {
while (true) {
int i = in.read(tmp, 0, 1024);
if (i < 0) {
break;
}
String line = new String(tmp, 0, i, SshGetEncodeDOS.getEncode());
if ((line.contains("bytes") || line.contains("字节"))
&& (line.contains("time") || line.contains("时间"))
&& (line.contains("ttl") || line.contains("TTL"))) {
return true;
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return false;
}
}单次运行或者几十次运行都没问题,但是一旦多次运行(比如说for循环运行10000次,大概100次左右就会ping不通,)这是什么原因?求解JavaLinux