public static ServerSocket getSocketInRange ( int minPort , int maxPort , boolean random ) { TCPUtils . Log ( Level . INFO , "Attempting to create a ServerSocket in range (" + minPort + "-" + maxPort + ( random ? ") at random..." : ") sequentially..." ) ) ; ServerSocket s = null ; int port = minPort - 1 ; Random r = new Random ( System . currentTimeMillis ( ) ) ; while ( s == null && port <= maxPort ) { if ( random ) port = minPort + r . nextInt ( maxPort - minPort ) ; else port ++ ; try { TCPUtils . Log ( Level . INFO , " - trying " + port + "..." ) ; s = new ServerSocket ( port ) ; TCPUtils . Log ( Level . INFO , "Succeeded!" ) ; return s ; // Created okay, so this port is available. } catch ( IOException e ) { // Try the next port. TCPUtils . Log ( Level . INFO , " - failed: " + e ) ; } } TCPUtils . Log ( Level . SEVERE , "Could find no available port!" ) ; return null ; // No port found in the allowed range. }
Choose a port from the specified range - either sequentially or at random .