/***************************************
 *                                     *
 *  JBoss: The OpenSource J2EE WebOS   *
 *                                     *
 *  Distributable under LGPL license.  *
 *  See terms of license at gnu.org.   *
 *                                     *
 ***************************************/
package org.jboss.remoting.transport;

import java.net.ServerSocket;

/**
 * PortUtil is a set of utilities for dealing with TCP/IP ports
 *
 * @author <a href="mailto:jhaynie@vocalocity.net">Jeff Haynie</a>
 * @version $Revision: 1.1 $
 */
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
        {
            // try and open port,
            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;
        }
        //start where we left off
        for ( int c = lastPort; c < 64000; c++ )
        {
            if ( testPort ( c ) )
            {
                lastPort = c + 1;
                return c;
            }
        }
        // start back at top
        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 ();
        }
    }
}
