Randeep
Randeep

Reputation: 543

Getting the ping results using java

I'm trying to get the last line of the ping result. I'm not a java developer. I'm learning so please bear my mistakes.

This is the program I have written.

private static String pingTest(String ip) {
    // TODO Auto-generated method stub
    String pingResult = "";
//  System.out.println("Came in pingTest");
    String pingCmd = "ping -c 3 " + 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);
    }
    return pingResult;

I'm getting the result as follows:

PING google.com (74.125.236.165) 56(84) bytes of data.64 bytes from maa03s16-in-f5.1e100.net (74.125.236.165): icmp_req=1 ttl=52 time=20.5 ms64 bytes from maa03s16-in-f5.1e100.net (74.125.236.165): icmp_req=2 ttl=52 time=11.4 ms64 bytes from maa03s16-in-f5.1e100.net (74.125.236.165): icmp_req=3 ttl=52 time=19.6 ms--- google.com ping statistics ---3 packets transmitted, 3 received, 0% packet loss, time 2002msrtt min/avg/max/mdev = 11.494/17.252/20.579/4.089 m

Its ot properly formatted. how to add line breaks? Well. what I really want is something like this.

Only the last line.

rtt min/avg/max/mdev = 20.774/20.962/21.085/0.135 ms

and I want to show the values of min,avg,max values in my jsp page. Please guide me.

Upvotes: 0

Views: 1272

Answers (2)

Randeep
Randeep

Reputation: 543

Update: I updated the code. Now I'm getting only last line as output.

private static String pingTest(String ip) {
    // TODO Auto-generated method stub
    String pingResult = "";
//  System.out.println("Came in pingTest");
    String pingCmd = "ping -c 3 " + 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);
            if (inputLine.contains("rtt"))
            pingResult += inputLine+ "\n";
            }
        in.close();
    } catch (IOException e) {
        System.out.println(e);
    }
    return pingResult;

}

Thanks

Upvotes: 0

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136042

try

pingResult += inputLine + "\n";

note that it's typical to use StringBuilder in such situations, no matter what perfomance impact is

Upvotes: 1

Related Questions