Thursday 29 June 2017

Ping an IP address in Java | Java Networking

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

2 comments:

  1. First I want to tell you Thank you for sharing it with us.
    I am really Happy and impressed to see this blog!
    law essay writing help

    ReplyDelete
  2. Great!
    Such a wonderful and helpful blog for me.
    Thank you for sharing it with us.
    Buy Law Essay UK

    ReplyDelete

Related Posts Plugin for WordPress, Blogger...