Sockets: Discover port availability using Java

2019-01-01 10:50发布

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?.

9条回答
临风纵饮
2楼-- · 2019-01-01 11:26

The try/catch socket based solutions , might not yield accurate results (the socket address is "localhost" and in some cases the port could be "occupied" not by the loopback interface and at least on Windows I've seen this test fails i.e. the prot falsely declared as available).

There is a cool library named SIGAR , the following code can hook you up :

Sigar sigar = new Sigar();
int flags = NetFlags.CONN_TCP | NetFlags.CONN_SERVER | NetFlags.CONN_CLIENT;             NetConnection[] netConnectionList = sigar.getNetConnectionList(flags);
for (NetConnection netConnection : netConnectionList) {
   if ( netConnection.getLocalPort() == port )
        return false;
}
return true;
查看更多
几人难应
3楼-- · 2019-01-01 11:27

If you're not too concerned with performance you could always try listening on a port using the ServerSocket class. If it throws an exception odds are it's being used.

boolean portTaken = false;
    ServerSocket socket = null;
    try {
        socket = new ServerSocket(_port);
    } catch (IOException e) {
        portTaken = true;
    } finally {
        if (socket != null)
            try {
                socket.close();
            } catch (IOException e) { /* e.printStackTrace(); */ }
}

EDIT: If all you're trying to do is select a free port then new SocketServer(0) will find one for you.

查看更多
妖精总统
4楼-- · 2019-01-01 11:32

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);              
    }
查看更多
登录 后发表回答