如何运行PING命令并获取ping主机摘要?

时间:2012-01-11 06:20:37

标签: java command-line ping

您好我需要使用Java代码执行PING命令并获取ping主机的摘要。如何用Java做到这一点?

4 个答案:

答案 0 :(得分:14)

作为指定的viruspatel,您可以使用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

答案 1 :(得分:3)

InetAddress类有一个方法,它使用ECMP Echo Request(aka ping)来确定主机的可用性。

String ipAddress = "192.168.1.10";
InetAddress inet = InetAddress.getByName(ipAddress);
boolean reachable = inet.isReachable(5000);

如果上述reachable变量为真,则表示主机已在给定时间内(毫秒)正确回答了ECMP Echo Reply(aka pong)。

注意:并非所有实现都必须使用ping。 The documentation states that

  

如果是特权,典型的实现将使用ICMP ECHO REQUEST   可以获得,否则它将尝试建立TCP连接   在目标主机的端口7(Echo)上。

因此,该方法可用于检查主机可用性,但不能普遍用于检查基于ping的检查。

答案 2 :(得分:1)

查看我正在制作的这个ping库:

http://code.google.com/p/jpingy/

也许它可以提供帮助

答案 3 :(得分:0)

下面的代码在Windows和Linux系统上均可使用,

public static boolean isReachable(String url) throws MalformedURLException {
        if (!url.contains("http") && !url.contains("https")) {
            url = "http://" + url;
        }
        URL urlObj = new URL(url);
        url = urlObj.getHost();
        url = "ping " + url;
        try {
            Process p = Runtime.getRuntime().exec(url);
            BufferedReader inputStream = new BufferedReader(
                    new InputStreamReader(p.getInputStream()));
            String s = "";
            while ((s = inputStream.readLine()) != null) {
                if (s.contains("Packets: Sent") || s.contains("bytes of data")) {
                    return true;
                }
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }