在SSH隧道中创建转发端口

我正在尝试使用SSH.NET从localhost:3306创建隧道localhost:3306到远程计算机上的端口3306:

  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(); } 

当命中断点时, client.IsConnected返回true ,但telnet localhost 3306没有连接。 如果我使用Putty创建连接,并在那里设置相同的隧道,则成功。 我错过了什么?

通过将ForwardedPortLocal的参数更改为:

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

(使其明确指向我绑定的接口),并在port.Start();之前添加以下代码port.Start();

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

我注意到以下输出:

  ::1:60309 

e.OriginatorHost部分是::1 ,它是localhost的IPv6等价物; 但是,目标服务器使用的是IPv4。 将参数更改为:

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

强迫隧道在IPv4上运行,然后我的代码完全像我预期的那样工作。

在遇到同样的问题并对其进行分析之后,考虑到我得出的结论是它是一个错误(虽然它可能被认为是有争议的,但显然这种行为让SSH.NET API的用户感到惊讶)。

所以我在本地隧道上报告了意外行为(又名bug)·问题#117·sshnet / SSH.NET·GitHub 。

在修复之前, c#中的解决方法- 在SSH隧道中创建转发端口 – Stack Overflow工作。