private static boolean isAvailable ( int thePort ) { ourLog . info ( "Testing a bind on thePort {}" , thePort ) ; try ( ServerSocket ss = new ServerSocket ( ) ) { ss . setReuseAddress ( true ) ; ss . bind ( new InetSocketAddress ( "0.0.0.0" , thePort ) ) ; try ( DatagramSocket ds = new DatagramSocket ( ) ) { ds . setReuseAddress ( true ) ; ds . connect ( new InetSocketAddress ( "127.0.0.1" , thePort ) ) ; ourLog . info ( "Successfully bound thePort {}" , thePort ) ; } catch ( IOException e ) { ourLog . info ( "Failed to bind thePort {}: {}" , thePort , e . toString ( ) ) ; return false ; } } catch ( IOException e ) { ourLog . info ( "Failed to bind thePort {}: {}" , thePort , e . toString ( ) ) ; return false ; } try ( ServerSocket ss = new ServerSocket ( ) ) { ss . setReuseAddress ( true ) ; ss . bind ( new InetSocketAddress ( "localhost" , thePort ) ) ; } catch ( IOException e ) { ourLog . info ( "Failed to bind thePort {}: {}" , thePort , e . toString ( ) ) ; return false ; } return true ; }
This method checks if we are able to bind a given port to both 0 . 0 . 0 . 0 and localhost in order to be sure it s truly available .