Java: Simple check to see if a server is listening on a port

Here is a simple method to check if a server is listening on a certain port. I used it to ignore certain non-critical SFTP related integration tests in a project when I hadn’t bothered starting the SFTP server.

public static boolean serverListening(String host, int port)
{
    Socket s = null;
    try
    {
        s = new Socket(host, port);
        return true;
    }
    catch (Exception e)
    {
        return false;
    }
    finally
    {
        if(s != null)
            try {s.close();}
            catch(Exception e){}
    }
}

To ignore a test (assuming JUnit) you can then do the following:

@Test
public void some_test()
{
    assumeTrue(serverListening("localhost", 22));

    // Rest of test...
}
  • Shane K

    Thanks for this. I implemented a version of this code within an async callback block, works perfectly.