@ Nonnull public static ENetworkPortStatus checkPortOpen ( @ Nonnull @ Nonempty final String sHostName , @ Nonnegative final int nPort , @ Nonnegative final int nTimeoutMillisecs ) { ValueEnforcer . notEmpty ( sHostName , "Hostname" ) ; ValueEnforcer . isGE0 ( nPort , "Port" ) ; ValueEnforcer . isGE0 ( nTimeoutMillisecs , "TimeoutMillisecs" ) ; LOGGER . info ( "Checking TCP port status for " + sHostName + ":" + nPort + " with timeouf of " + nTimeoutMillisecs + " ms" ) ; try ( final Socket aSocket = new Socket ( ) ) { aSocket . setReuseAddress ( true ) ; final SocketAddress aSocketAddr = new InetSocketAddress ( sHostName , nPort ) ; aSocket . connect ( aSocketAddr , nTimeoutMillisecs ) ; return ENetworkPortStatus . PORT_IS_OPEN ; } catch ( final IOException ex ) { // Can also be: // Connection refused: connect if ( ex . getMessage ( ) . startsWith ( "Connection refused" ) ) return ENetworkPortStatus . PORT_IS_CLOSED ; if ( ex instanceof java . net . UnknownHostException ) return ENetworkPortStatus . HOST_NOT_EXISTING ; if ( ex instanceof java . net . SocketTimeoutException ) return ENetworkPortStatus . CONNECTION_TIMEOUT ; if ( ex instanceof java . net . ConnectException ) { // E.g. for port 0 return ENetworkPortStatus . GENERIC_IO_ERROR ; } LOGGER . error ( "Other error checking TCP port status" , ex ) ; return ENetworkPortStatus . GENERIC_IO_ERROR ; } }
Check the status of a remote port .