Thursday, 29 June 2017

Ping an IP address in Java | Java Networking

We can ping an IP address using 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.

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("Print error (if any): ");
           while((s = error.readLine()) != null) {

     public static void main(String args[]) throws Exception {
           /** Initialize the command list. */
           ArrayList<String> commandList = new ArrayList<String>();

Ping result:
Pinging [] with 32 bytes of data:
Reply from bytes=32 time=403ms TTL=45
Reply from bytes=32 time=341ms TTL=45
Reply from bytes=32 time=359ms TTL=45
Reply from bytes=32 time=329ms TTL=45

Ping statistics for
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 329ms, Maximum = 403ms, Average = 358ms

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...