prüfen ob ip adresse erreichbar java code example

Example: prüfen ob ip adresse erreichbar java

import java.net.*;

public class SimplePing
{
  public static void main( String[] args )
  {
    System.out.println( "\nUsage: java SimplePing host [port] \n" +
                        " e.g.: java SimplePing www.torsten-horn.de \n" +
                        "   or: java SimplePing 1.2.3.4 80 \n" );
    try {
      if( args.length <= 0 )
        throw new Exception( "Parameter missing!" );
      InetAddress host = InetAddress.getByName( args[0] );
      int         port = ( args.length > 1 ) ? Integer.parseInt( args[1] ) : 80;
      long        tm   = System.nanoTime();
      Socket      so   = new Socket( host, port );
      so.close();
      tm = (System.nanoTime() - tm) / 1000000L;
      System.out.println( "Connection ok (port " + port + ", time = " + tm + " ms). \n" +
                          "Host Address = " + host.getHostAddress() + "\n" +
                          "Host Name    = " + host.getHostName() );
      System.exit( 0 );
    } catch( Exception ex ) {
      System.out.println( "Error: " + ex.getMessage() );
      System.exit( 1 );
    }
  }
}

Tags:

Java Example