Skip to content

Instantly share code, notes, and snippets.

@chilversc
Created March 11, 2015 16:59
Show Gist options
  • Save chilversc/b077b43554d54ed2200f to your computer and use it in GitHub Desktop.
Save chilversc/b077b43554d54ed2200f to your computer and use it in GitHub Desktop.
SSH Tunnel with a dynamically allocated local port in C# using SSH.NET
class SshTunnel : IDisposable
{
private SshClient client;
private ForwardedPortLocal port;
private int localPort;
public SshTunnel (ConnectionInfo connectionInfo, uint remotePort)
{
try {
client = new SshClient (connectionInfo);
// using 0 for the client port to dynamically allocate it
port = new ForwardedPortLocal ("127.0.0.1", 0, "127.0.0.1", remotePort);
client.Connect ();
client.AddForwardedPort(port);
port.Start();
// HACK to get the dynamically allocated client port
var listener = (TcpListener) typeof (ForwardedPortLocal).GetField ("_listener", BindingFlags.Instance | BindingFlags.NonPublic).GetValue (port);
localPort = ((System.Net.IPEndPoint) listener.LocalEndpoint).Port;
} catch {
Dispose ();
throw;
}
}
public int LocalPort { get { return localPort; } }
public void Dispose ()
{
if (port != null)
port.Dispose ();
if (client != null)
client.Dispose ();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment