/*
 * JBoss, Home of Professional Open Source
 * Copyright 2005, JBoss Inc., and individual contributors as indicated
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.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.4.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 ();
        }
    }
}
