Created
March 11, 2015 16:59
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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