Sample Source Code:
Like what was earlier said, I port is free now does not mean that it will be free later. A port is blocked now does not mean that it will not be free later.
import java.net.*;
import java.io.*;
public class Test {
public static final String NEWLINE = System.getProperty( "line.separator" );
public void tryToConnect(InetAddress address, int port ) {
try
{
Socket socket = new Socket( address, port );
socket.close();
System.out.println( "Connected successfully to " + address + " : " + port );
}
catch ( Exception ex )
{
System.out.println( "Error attempting to connect to " + address + " : " + port + " with exception : " + ex.getMessage() );
}
}
public void tryToConnect(String host, int port ) {
try
{
InetAddress address = InetAddress.getByName( host );
Socket socket = new Socket( address, port );
socket.close();
System.out.println( "Connected successfully to " + host + " : " + port );
}
catch ( Exception ex )
{
System.out.println( "Error attempting to connect to " + host + " : " + port + " with exception : " + ex.getMessage() );
}
}
public static void main( String[] args ) throws Exception {
System.out.println( "Starting the test" );
Test test = new Test();
test.tryToConnect( "localhost", 80 );
System.out.println( "Done with the test" );
}
}