Java: Ping application

Here is a code to call ping command on windows using java. The question would be, why not to ping directly from ms-dos window? 🙂

The answer is because this application produces a beep sound when the target is not found. So, it is useful when connections are problematic.

When the connection recovers again, the beep sound stops.

It pings without stop sending the minimum package, so it does not consume any bandwidth.

import java.io.*;
import java.util.*;
import java.awt.Toolkit;

public class JavaPingExampleProgram
{

  public static void main(String args[])
  throws IOException
  {
    

    // create the ping command as a list of strings
    JavaPingExampleProgram ping = new JavaPingExampleProgram();
    List<String> commands = new ArrayList<String>();
    commands.add("ping");

    commands.add("-l");
    commands.add("2");
    commands.add("-t");
    commands.add("google.com");
    ping.doCommand(commands);
  }


  public void doCommand(List<String> command)
  throws IOException
  {
    String s = null;

    ProcessBuilder pb = new ProcessBuilder(command);
    Process process = pb.start();

    BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));

    BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));

    // read the output from the command
    System.out.println("Here is the standard output of the command:\n");

    while ((s = stdInput.readLine()) != null)
    {
      if(s.equals("Request timed out.")){
          Toolkit.getDefaultToolkit().beep();
      }else if(s.indexOf("Destination host unreachable")>0){

          Toolkit.getDefaultToolkit().beep();
      }   
      System.out.println(s);
    }

    // read any errors from the attempted command
    System.out.println("Here is the standard error of the command:\n");

    while ((s = stdError.readLine()) != null)
    {
      System.out.println(s);
      Toolkit.getDefaultToolkit().beep();
    }
  }
}

Leave a Reply