Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run PING command and get ping host summary?

Hi I need to execute the PING command using Java code and get summary of the ping host. How to do it in Java?

like image 947
Salman Raza Avatar asked Jan 11 '12 06:01

Salman Raza


People also ask

What is the output of ping command?

The ping command sends one datagram per second and prints one line of output for every response received. The ping command calculates round-trip times and packet loss statistics, and displays a brief summary on completion.


3 Answers

as viralpatel specified you can use Runtime.exec()

following is an example of it

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);
        }

    }
}

output

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

refer http://www.velocityreviews.com/forums/t146589-ping-class-java.html

like image 104
Hemant Metalia Avatar answered Nov 14 '22 22:11

Hemant Metalia


InetAddress class has a method which uses ECMP Echo Request (aka ping) to determine the hosts availability.

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

If the above reachable variable is true, then it means that the host has properly answered with ECMP Echo Reply (aka pong) within given time (in millis).

Note: Not all implementations have to use ping. The documentation states that:

A typical implementation will use ICMP ECHO REQUESTs if the privilege can be obtained, otherwise it will try to establish a TCP connection on port 7 (Echo) of the destination host.

Therefore the method can be used to check hosts availability, but it can not universally be used to check for ping-based checks.

like image 25
Dariusz Avatar answered Nov 14 '22 20:11

Dariusz


Check out this ping library for java I'm making:

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

Maybe it can help

like image 45
tgoossens Avatar answered Nov 14 '22 21:11

tgoossens