Created
September 25, 2018 02:57
-
-
Save iamdylanngo/210ae2082e96d1fa7a4a0e022e388754 to your computer and use it in GitHub Desktop.
SSHTunnel SSH.NET connect SSH and forward Socks 5
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
using Renci.SshNet; | |
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Net.Sockets; | |
using System.Reflection; | |
using System.Text; | |
namespace ToolSSH | |
{ | |
public 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