package org.jboss.remoting.transport;
import java.net.ServerSocket;
public class PortUtil
{
private static final int START_PORT_RANGE = Integer.parseInt ( System.getProperty ( "jboss.remoting.start.portrange", "5000" ) );
private static int lastPort = START_PORT_RANGE;
private static boolean testPort ( int p )
{
ServerSocket socket = null;
try
{
socket = new ServerSocket ( p );
return true;
}
catch ( Exception ex )
{
}
finally
{
if ( socket != null )
{
try
{
socket.close ();
}
catch ( Exception ig )
{
}
socket = null;
}
}
return false;
}
public static int findFreePort ()
{
if ( lastPort > 64000 )
{
lastPort = START_PORT_RANGE;
}
for ( int c = lastPort; c < 64000; c++ )
{
if ( testPort ( c ) )
{
lastPort = c + 1;
return c;
}
}
for ( int c = START_PORT_RANGE; c < lastPort; c++ )
{
if ( testPort ( c ) )
{
lastPort = c + 1;
return c;
}
}
throw new RuntimeException ( "Couldn't find a free TCP/IP port" );
}
public static void main ( String args[] )
{
try
{
System.out.println ( "port - " + findFreePort () );
}
catch ( Exception ex )
{
ex.printStackTrace ();
}
}
}