Tuesday, 29 April 2014

Ping Command in Java


import java.io.*;
import java.net.*;

class PingEx{
 static String hostAddress;
 static int timeOut;
 
 void pingMachine(String addr, int timeOut)throws Exception{
  boolean status;
  status = InetAddress.getByName(addr).isReachable(timeOut);
  
  if(status == true){
   System.out.println("Machine is pinging");
  }
  else{
   System.out.println("Machine is not pinging");
  }
 }
 
 public static void main(String args[])throws Exception{
  BufferedReader br;
  
  PingEx obj1 = new PingEx();
  br = new BufferedReader(new InputStreamReader(System.in));
  
  System.out.println("Enter Machine IP or name");
  hostAddress = br.readLine();
  
  System.out.println("Enter time out");
  timeOut = Integer.parseInt(br.readLine());
  
  obj1.pingMachine(hostAddress, timeOut);
 }
}

Sample Runs
Run 1
Enter Machine IP
1.2.3.4
Enter time out
10000
Machine is not pinging


Run 2
java PingEx
Enter Machine IP
abc.in.abc.com
Enter time out
10000
Machine is pinging



                                                             Home

No comments:

Post a Comment