在编写网管系统的过程中,经常需要判断某台机器是否可用,于是采用使用ping机器的方法判断该机器当前是否可用,方法如下:
/**
* @Title: execPingCommand
* @Description: 执行ping命令,查看设备是否可用
* @param @param deviceIp
* @return boolean true-能ping通,false-不能ping通
* @throws
*/
public static boolean execPingCommand(String deviceIp){
logger.debug("enter VolumeManage.execPingCommand(String deviceIp) ");
boolean networkUseable = false;
//String address="www.javawind.net";
Process process = null;
try {
process = Runtime.getRuntime().exec("ping -c 3 "+deviceIp);
} catch (IOException e1) {
// TODO Auto-generated catch block
logger.error("System error: ", e1);
}
InputStreamReader r = new InputStreamReader(process.getInputStream());
LineNumberReader returnData = new LineNumberReader(r);
String returnMsg="";
String line = "";
try {
while ((line = returnData.readLine()) != null) {
//System.out.println(line);
returnMsg += line;
}
if(returnMsg.indexOf("Unreachable") != -1 || returnMsg.indexOf("100% packet loss") != -1){
networkUseable = false;
}
else{
networkUseable = true;
}
}catch (IOException e) {
// TODO Auto-generated catch block
logger.error("System error: ", e);
} finally{
if(returnData != null){
try {
returnData.close();
} catch (IOException e) {
// TODO Auto-generated catch block
logger.error("System error: ", e);
}
}
if(r != null){
try {
r.close();
} catch (IOException e) {
// TODO Auto-generated catch block
logger.error("System error: ", e);
}
}
}
logger.debug("exit VolumeManage.execPingCommand(String deviceIp) " + "[networkUseable] = " + networkUseable);
return networkUseable;
}
此方法关键命令为红色部分:ping -c 3 + ip;这个命令为linux系统所有,windows上不能执行,表示方法执行之后,只需要返回3行响应消息便可,不然在linux中,如果不终止该命令,会不停的打印响应的消息。
ping通机器的响应消息如下:
[root@abc ~]# ping -c 3 192.168.3.51
PING 192.168.3.51 (192.168.3.51) 56(84) bytes of data.
64 bytes from 192.168.3.51: icmp_seq=1 ttl=64 time=14.6 ms
64 bytes from 192.168.3.51: icmp_seq=2 ttl=64 time=0.332 ms
64 bytes from 192.168.3.51: icmp_seq=3 ttl=64 time=0.359 ms
--- 192.168.3.51 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2000ms
rtt min/avg/max/mdev = 0.332/5.103/14.619/6.728 ms
[root@abc ~]#
ping不同的机器的响应消息如下:
[root@abc ~]# ping -c 3 192.168.3.52
PING 192.168.3.52 (192.168.3.52) 56(84) bytes of data.
From 192.168.7.181 icmp_seq=1 Destination Host Unreachable
From 192.168.7.181 icmp_seq=2 Destination Host Unreachable
From 192.168.7.181 icmp_seq=3 Destination Host Unreachable
--- 192.168.3.52 ping statistics ---
3 packets transmitted, 0 received, +3 errors, 100% packet loss, time 2000ms
, pipe 3
[root@abc ~]#
因此,方法根据这两个条件进行判断,如果含有Unreachable或者100% packet loss就表示机器ping不同,不可用,否则为可用。