14

我正在尝试使用SSH.NETlocalhost: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 创建连接,并在那里设置相同的隧道,它会成功。我错过了什么?

4

2 回答 2

19

通过将 ForwardedPortLocal 的参数更改为:

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

(以明确我绑定到哪个接口),并在之前添加以下代码port.Start();

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

我注意到以下输出:

    ::1:60309

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

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

迫使隧道改为在 IPv4 上运行,然后我的代码完全按照我的预期工作。

于 2013-08-29T10:40:02.480 回答
0

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

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

在修复之前,c# 中的解决方法 - 在 SSH 隧道中创建转发端口 - 堆栈内存溢出

于 2016-11-16T19:37:50.917 回答