We
can ping an IP address using java.net.InetAddress.isReachable() method.
This
example is by using ProcessBuilder class, Process class. ProcessBuilder class
is used to create operating system processes and ProcessBuilder.start() starts
the sub-process which will execute the ping command.
package com.java.networking;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class PingIP {
static void
runOSCommands(ArrayList<String> commandList) throws Exception {
/** creating the sub process, execute
system command. */
ProcessBuilder build = new
ProcessBuilder(commandList);
Process process = build.start();
/** to read the output. */
BufferedReader input = new
BufferedReader(new InputStreamReader(process.getInputStream()));
BufferedReader error = new
BufferedReader(new InputStreamReader(process.getErrorStream()));
String s = null;
System.out.println("Ping result: ");
while((s = input.readLine()) != null)
{
System.out.println(s);
}
System.out.println("Print error (if any): ");
while((s = error.readLine()) != null)
{
System.out.println(s);
}
}
public static void main(String args[]) throws Exception {
/** Initialize the command list. */
ArrayList<String> commandList = new
ArrayList<String>();
commandList.add("ping");
commandList.add("www.google.com");
runOSCommands(commandList);
}
}
Ping result:
Pinging
www.google.com [74.125.68.104] with 32 bytes of data:
Reply from
74.125.68.104: bytes=32 time=403ms TTL=45
Reply from
74.125.68.104: bytes=32 time=341ms TTL=45
Reply from
74.125.68.104: bytes=32 time=359ms TTL=45
Reply from
74.125.68.104: bytes=32 time=329ms TTL=45
Ping statistics for
74.125.68.104:
Packets: Sent = 4, Received = 4, Lost = 0
(0% loss),
Approximate round
trip times in milli-seconds:
Minimum = 329ms, Maximum = 403ms, Average =
358ms