Friday, May 11, 2012

Basic IP Check with Ping using Java



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.UnknownHostException;


public class testIp {

public static boolean checkIp (String sip)
  {
      String [] parts = sip.split ("\\.");
      System.out.println("Parts length is "+parts.length);
      if ( parts.length != 4 )
      {
          return false;
      }
      for (String s : parts)
      {
          int i = Integer.parseInt (s);
          if (i < 0 || i > 255)
          {
              return false;
          }
      }
      if (pingIp(sip))
      return true;
      else
      return false;
  }

private static boolean pingIp(String sip) {
// TODO Auto-generated method stub
try {
InetAddress adr = InetAddress.getByName(sip);
boolean stat= adr.isReachable(2000);
return stat;
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return false;
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Enter the IP to be chacked");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {

String line = br.readLine();
boolean status=testIp.checkIp(line);
System.out.println("Status is "+status);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}




No comments:

Post a Comment