public static int getAvailablePort ( ) { for ( int i = 0 ; i < 50 ; i ++ ) { try ( ServerSocket serverSocket = new ServerSocket ( 0 ) ) { int port = serverSocket . getLocalPort ( ) ; if ( port != 0 ) { return port ; } } catch ( IOException ignored ) { } } throw new RuntimeException ( "Could not find a free permitted port on the machine." ) ; }
Find a non - occupied port .