Skip to content

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

@oakkitten

Description

@oakkitten

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();

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions