Hi I need to execute the PING
command using Java code and get summary of the ping host. How to do it in Java?
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.
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
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.
Check out this ping library for java I'm making:
http://code.google.com/p/jpingy/
Maybe it can help
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With