Adrian Wragg Adrian Wragg - 3 months ago 28
C# Question

Creating a forwarded port within an SSH tunnel

I'm attempting to use SSH.NET to create a tunnel from

to port 3306 on a remote machine:

PrivateKeyFile file = new PrivateKeyFile(@" .. path to private key .. ");
using (var client = new SshClient(" .. remote server .. ", "ubuntu", file))

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

// breakpoint set within the code here


When the breakpoint is hit,
is returning
, but
telnet localhost 3306
is not connecting. If I create the connection using Putty instead, and set up the same tunnel there, it succeeds. What have I missed?


By changing the parameters of ForwardedPortLocal to:

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

(to make it explicit which interface I was binding to), and adding the following code in just before port.Start();:

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

I noticed the following being output:


The e.OriginatorHost part of this was ::1, which is the IPv6 equivalent of localhost; however, the destination server was using IPv4. Changing the parameters to:

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

forced the tunnel to run over IPv4 instead, and my code then worked exactly as I'd expected it to.