public static int getRandomPort ( ) { try { ServerSocket socket = new ServerSocket ( 0 ) ; try { return socket . getLocalPort ( ) ; } finally { socket . close ( ) ; } } catch ( IOException e ) { return - 1 ; } }
Find a random free port in localhost for binding .