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

How to bind random local port for simple port forwarding? #362

Open
x1a0 opened this issue Oct 17, 2024 · 2 comments
Open

How to bind random local port for simple port forwarding? #362

x1a0 opened this issue Oct 17, 2024 · 2 comments

Comments

@x1a0
Copy link

x1a0 commented Oct 17, 2024

Hi,

I am trying to use the channel_open_direct_tcpip method to open a simple local port forwarding, and got 2 questions:

  • Is it possible to get a random available local port?
  • In my case, I just want to open the local port, so a database client is able to use it to talk to the database via the tunnel. aka I do not really want/need to handle anything via the russh channel. Is it possible?

Thanks

@Eugeny
Copy link
Owner

Eugeny commented Oct 18, 2024

You might be confused by the difference in concepts between the OpenSSH client and the protocol itself. You don't need to open a local port if you just want to connect to somewhere on the remote side via direct-tcpip, you can just do it without listening on the local side first.

The reason why the OpenSSH client does this is because that's the only usable way to do it in a general purpose CLI client

If you just want to connect to a remote database, use channel_open_direct_tcpip, turn your channel into a stream via Channel::into_stream and pass that to your database client library.

@dcormier
Copy link

dcormier commented Dec 6, 2024

  • Is it possible to get a random available local port?

Yes. Specify port 0 as the port to listen on. Most OS's (Linux, Windows, macOS, at least) will assign a random available port. Example:

use tokio::net::TcpListener;

#[tokio::main]
async fn main()  {
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();

    println!("Listening on port {}", listener.local_addr().unwrap().port());
}

Output (will vary from run to run):

Listening on port 44923

You can then pass that TcpListener to Server::run_on_socket().

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

No branches or pull requests

3 participants