protected int getFreePort ( ) { ServerSocket ss ; int freePort = 0 ; for ( int i = 0 ; i < 10 ; i ++ ) { freePort = ( int ) ( 10000 + Math . round ( Math . random ( ) * 10000 ) ) ; freePort = freePort % 2 == 0 ? freePort : freePort + 1 ; try { ss = new ServerSocket ( freePort ) ; freePort = ss . getLocalPort ( ) ; ss . close ( ) ; return freePort ; } catch ( IOException e ) { LOGGER . log ( Level . WARNING , "exception" , e ) ; } } try { ss = new ServerSocket ( 0 ) ; freePort = ss . getLocalPort ( ) ; ss . close ( ) ; } catch ( IOException e ) { LOGGER . log ( Level . WARNING , "exception" , e ) ; } return freePort ; }
Obtain a free port we can use .