参考 : 使用Java获取ping结果 - IT屋-程序员软件开发技术分享社区
代码
import org.apache.commons.lang3.exception.ExceptionUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
public class PingUtil {
/**
* 判断是否通
*
* @param ipAddress
* @return
*/
public static boolean ping(String ipAddress) {
try {
// 超时
int timeOut = 2000;
boolean status = InetAddress.getByName(ipAddress).isReachable(timeOut);
// 当返回值是true时,说明host是可用的,false则不可。
return status;
} catch (Exception e) {
System.out.println("ping {} 失败,error:"+ ipAddress+ ExceptionUtils.getStackTrace(e));
return Boolean.FALSE;
}
}
/**
* 判断是否通
*
* @param ipAddress
* @return
*/
public static boolean pingResult(String ipAddress, int timeOut) {
try {
boolean status = InetAddress.getByName(ipAddress).isReachable(timeOut);
// 当返回值是true时,说明host是可用的,false则不可。
return status;
} catch (Exception e) {
System.err.println("ping {} 失败,error:{}"+ ipAddress+ ExceptionUtils.getStackTrace(e));
return Boolean.FALSE;
}
}
/**
* 测试ip及端口连通性
*
* @param host
* @param port
* @param timeout
* @return boolean
*/
public static boolean testIpAndPort(String host, int port, int timeout) {
Socket s = new Socket();
boolean status = false;
try {
s.connect(new InetSocketAddress(host, port), timeout);
status = true;
} catch (IOException e) {
System.out.println(host + ":" + port + "无法访问!");
} finally {
try {
s.close();
} catch (IOException ex) {
System.out.println("关闭socket异常" + ex);
}
}
return status;
}
/**
* 获取 ping 结果
*
* @param ip
* @param count 发包次数
* @return
*/
public static String ping(String ip, int count) {
String pingResult = "";
String pingCmd = "ping -c " + count + " " + ip;
BufferedReader in = null;
try {
Runtime r = Runtime.getRuntime();
Process p = r.exec(pingCmd);
in = new BufferedReader(new
InputStreamReader(p.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
pingResult += inputLine + "\n";
}
} catch (Exception e) {
System.err.println(ExceptionUtils.getStackTrace(e));
} finally {
if (in != null) {
try {
in.close();
} catch (Exception ex) {
System.err.println(ExceptionUtils.getStackTrace(ex));
}
}
}
return pingResult;
}
}
maven依赖
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
EDN。