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

Offer/expose dynamic port assignment for ForwardedPortDynamic #1575

Open
TimCantleBucherMunicipal opened this issue Jan 17, 2025 · 1 comment

Comments

@TimCantleBucherMunicipal

I understand that in some TCP stacks, if you listen on port "0", a randomly-chosen and available port will be provided for you.

I would like to be able to use port=0 in ForwardedPortDynamic, to guarantee that an available port is chosen, and be able to use the actually bound port in later code. ForwardedPortDynamic does not update BoundHost or BoundPort after the socket starts listening.

using var sshClient = new SshClient(sshHost, sshPort, sshUser, sshPass);
await sshClient.ConnectAsync(token);

// I would like to do this
using var portForward = new ForwardedPortDynamic(0); 

// my current solution to choose a random (and hopefully available) port
// using var portForward = new ForwardedPortDynamic((uint)System.Random.Shared.Next(1024, 65535)); 

sshClient.AddForwardedPort(portForward);
portForward.Start();

// Use FluentFTP to connect to a remote server via the SOCKS proxy created by SSH.NET
var ftpClient = new AsyncFtpClientSocks5Proxy(new FtpProxyProfile()
{
    ProxyHost = "127.0.0.1",
    ProxyPort = (int)portForward.BoundPort,        // I need the port here, but it is still "0"
    FtpHost = ftpHost,
    FtpPort = (int)ftpPort,
    FtpCredentials = new NetworkCredential(ftpUser, ftpPass),
});

await ftpClient.Connect()

...

Is there a way to bind a random port that is guaranteed to be available and re-use it later?

@Rob-Hague
Copy link
Collaborator

I think it is probably just an oversight. The BoundPort is updated in ForwardedPortLocal:

// update bound port (in case original was passed as zero)
BoundPort = (uint)((IPEndPoint)_listener.LocalEndPoint).Port;

but not in ForwardedPortDynamic

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

2 participants