Creating a Forwarded Port in an SSH Tunnel

I am trying to use SSH.NET to create a tunnel from localhost:3306 to port 3306 on a remote machine:

  PrivateKeyFile file = new PrivateKeyFile(@" .. path to private key .. "); using (var client = new SshClient(" .. remote server .. ", "ubuntu", file)) { client.Connect(); var port = new ForwardedPortLocal(3306, "localhost", 3306); client.AddForwardedPort(port); port.Start(); // breakpoint set within the code here client.Disconnect(); } 

When the breakpoint hits, client.IsConnected returns true , but telnet localhost 3306 does not connect. If I create a connection using Putty instead and configure the same tunnel there, it will succeed. What did I miss?

+8
c # ssh portforwarding
source share
2 answers

By changing the ForwardedPortLocal parameters to:

  var port = new ForwardedPortLocal("localhost", 3306, "localhost", 3306); 

(to make it explicit what interface I was bound to) and adding the following code immediately before port.Start(); :

  port.RequestReceived += delegate(object sender, PortForwardEventArgs e) { Console.WriteLine(e.OriginatorHost + ":" + e.OriginatorPort); }; 

I noticed that the following is output:

  ::1:60309 

The e.OriginatorHost part was ::1 , which is equivalent to IPv6 localhost ; however, the destination server used IPv4. Change settings:

  var port = new ForwardedPortLocal("127.0.0.1", 3306, "localhost", 3306); 

made the tunnel work on top of IPv4, and my code worked exactly as I expected.

+10
source share

After hitting the same problem and analyzing it, and also considering that I came to the conclusion that this is a mistake (although this can be considered controversial, the behavior clearly surprises SSH.NET API users).

So, I reported this unexpected behavior (aka error) in the local tunnel · Problem No. 117 · sshnet / SSH.NET · GitHub .

Until it is fixed, a workaround in C # - creating a forwarded port in the SSH tunnel - stack overflow works.

0
source share

All Articles