您好,我需要使用Java代码执行PING命令,并获取ping主机的摘要。在Java中怎么做呢?
发布于 2012-01-11 14:34:26
正如viralpatel所指定的那样,您可以使用Runtime.exec()
下面是它的一个例子
class pingTest {
public static void main(String[] args) {
String ip = "127.0.0.1";
String pingResult = "";
String pingCmd = "ping " + ip;
try {
Runtime r = Runtime.getRuntime();
Process p = r.exec(pingCmd);
BufferedReader in = new BufferedReader(new
InputStreamReader(p.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
pingResult += inputLine;
}
in.close();
} catch (IOException e) {
System.out.println(e);
}
}
}输出
Pinging 127.0.0.1 with 32 bytes of data:
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Ping statistics for 127.0.0.1:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 0ms, Maximum = 0ms, Average = 0ms参考http://www.velocityreviews.com/forums/t146589-ping-class-java.html
发布于 2013-10-11 18:10:56
InetAddress类有一个使用ECMP Echo请求(又称ping)来确定主机可用性的方法。
String ipAddress = "192.168.1.10";
InetAddress inet = InetAddress.getByName(ipAddress);
boolean reachable = inet.isReachable(5000);如果上述reachable变量为true,则表示主机已在给定时间内(以毫秒为单位)正确地应答了ECMP Echo Reply (也称为pong)。
注意:并不是所有的实现都必须使用。The documentation states that
如果可以获得权限,典型的实现将使用
回应请求,否则它将尝试在目标主机的端口7(回应)上建立连接。
因此,该方法可用于检查主机可用性,但不能通用地用于检查基于ping的检查。
发布于 2012-08-19 06:10:22
看看我为java开发的这个ping库:
http://code.google.com/p/jpingy/
也许它能帮上忙
https://stackoverflow.com/questions/8815012
复制相似问题