在SSH隧道中创建转发端口

时间:2013-08-29 10:04:22

标签: c# ssh portforwarding ssh.net

我正在尝试使用SSH.NET在远程计算机上创建从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创建连接,并在那里设置相同的隧道,它就会成功。我错过了什么?

2 个答案:

答案 0 :(得分:17)

将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,即localhost的IPv6等价物;但是,目标服务器使用的是IPv4。将参数更改为:

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

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

答案 1 :(得分:0)

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

所以我在Unexpected behavior (a.k.a. bug) on local tunnel · Issue #117 · sshnet/SSH.NET · GitHub报告了它。

在修复之前,c# - Creating a forwarded port within an SSH tunnel - Stack Overflow中的解决方法有效。

相关问题