sshlib icon indicating copy to clipboard operation
sshlib copied to clipboard

Allow the system to choose local port when creating local port forwarder

Open oakkitten opened this issue 5 years ago • 0 comments

if you have a predefined port number, you can create a local port forwarder like this:

LocalPortForwarder forwarder = connection.createLocalPortForwarder(localPort, hostname, port);

the problem is that the port can be taken. you can try getting an unused port by doing something like this:

static int findAvailablePort() throws IOException {
    try (ServerSocket socket = new ServerSocket(0)) {
        return socket.getLocalPort();
    }
}

but it can lead to a race condition.

the solution would be to add a new api such as LocalPortForwarder.getLocalPort() or allow users to create ServerSockets themselves, as in

ServerSocket serverSocket = new ServerSocket(0);
connection.createLocalPortForwarder(serverSocket, hostname, port);
int localPort = serverSocket.getLocalPort();

oakkitten avatar Aug 29 '20 15:08 oakkitten