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