Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
oakkitten opened this issue Aug 29, 2020 · 0 comments

Comments

@oakkitten
Copy link
Contributor

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();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant