views:

1254

answers:

2

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+") ) );
    }

}
+2  A: 

The code is very reasonable. And since it's short, there isn't too much that must be cut out.

If I were coding the port scanner, I would remove the isInvalidInput method. Instead of that, I would assume the input was valid. If a user enters something that is not a valid integer, catch the parse error there and tell him to reenter it.

mcandre
+2  A: 

Enhanced ? If you're talking about the complexity of your code well : you don't have any loop (for,while), only 1 condition (if). So the complexity could hardly be reduced.

Since you're displaying the usage when the arguments, I'm assuming this will be used by user and not by another part of your own code. You need to keep this.

If you're worried about the time it takes to contact the host when it doesn't respond, you could set your own timeout. If you'nre not familiar with timeouts read this.

Your code is optimal for the case where the host responds.

It actually bugs me when it takes too much to connect. I have modified this version to handle optional parameter "timeout" Now I wonder if using "isUnresolved()" method is good or not. :)
OscarRyz
Careful : name resolving means to see if the hostname links to an ip address. It is not the same thing. For example www.google.com can be resolved to 66.102.1.147.
Silence
Also : the "else if ( args.length == 3 )" is useless because the system exits in the if. And don't leave empy catch (NumberFormatException)... it's not a good practice. If the user enters a value which is not a number your code will silently revert to 2000. Silence is good ;) but not in this case.
Silence