@ SuppressForbidden ( reason = "We want to bind to any address here when checking for free ports" ) public static int getNextFreePort ( int portRangeStart , int portRangeEnd ) throws IOException { for ( int port = portRangeStart ; port <= portRangeEnd ; port ++ ) { try ( ServerSocket sock = new ServerSocket ( ) ) { sock . setReuseAddress ( true ) ; sock . bind ( new InetSocketAddress ( port ) ) ; return port ; } catch ( IOException e ) { // seems to be taken, try next one log . warning ( "Port " + port + " seems to be used already, trying next one..." ) ; } } throw new IOException ( "No free port found in the range of [" + portRangeStart + " - " + portRangeEnd + "]" ) ; }
Method that is used to find the next available port . It used the two constants PORT_RANGE_START and PORT_RANGE_END defined above to limit the range of ports that are tried .