I'm using the following class to test if a host accepts connection from java
My question is, what could be enhanced here?
Thanks for the feedback
EDIT
I have added the optional parameter "timeout" in seconds.
import java.io.IOException;
import java.net.Socket;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
public class TestConnection {
public static void main( String [] args ) {
int timeout = 2000; // two seconds
if( isInvalidInput( args ) ) {
System.err.println("Usage: java TestConnection remotehost port [timeout_seconds]");
System.exit( -1 );
} else if ( args.length == 3 ) try {
timeout = Integer.parseInt( args[2] ) * 1000;
} catch( NumberFormatException nfe ){}
String host = args[0];
String port = args[1];
System.out.printf("Attempting: %s port: %s ....\n", host, port );
Socket socket = new Socket();
InetSocketAddress endPoint = new InetSocketAddress( host,
Integer.parseInt( port ) );
if ( endPoint.isUnresolved() ) {
System.out.println("Failure " + endPoint );
} else try {
socket.connect( endPoint , timeout );
System.out.printf("Success: %s \n", endPoint );
} catch( IOException ioe ) {
System.out.printf("Failure: %s message: %s - %s \n",
endPoint , ioe.getClass().getSimpleName(), ioe.getMessage());
} finally {
if ( socket != null ) try {
socket.close();
} catch( IOException ioe ) {}
}
}
/**
* Validates the number of arguments is exactly 2 and the second is a number.
* @return true is args.length == 2 && args[1].matches(\\d+);
*/
private static final boolean isInvalidInput( String [] args ) {
return ( args.length < 2
|| ( args.length >= 2 && !args[1].matches("\\d+") ) );
}
}