Alex Rivera | Logout

Sockets: Discover port availability using Java

Asked 2009-01-12T07:38:18.337
149

How do I programmatically determine the availability of a port in a given machine using Java?

i.e given a port number, determine whether it is already being used or not?.

Edit
Report

1 Answer

1

In my case it helped to try and connect to the port - if service is already present, it would respond.

    try {
        log.debug("{}: Checking if port open by trying to connect as a client", portNumber);
        Socket sock = new Socket("localhost", portNumber);          
        sock.close();
        log.debug("{}: Someone responding on port - seems not open", portNumber);
        return false;
    } catch (Exception e) {         
        if (e.getMessage().contains("refused")) {
            return true;
    }
        log.error("Troubles checking if port is open", e);
        throw new RuntimeException(e);              
    }
answered 2012-05-31T05:52:34.567

Your Answer