在SSH隧道中创建转发端口

Adr*_*agg 13 c# ssh portforwarding ssh.net

我正在尝试使用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();
  }
Run Code Online (Sandbox Code Playgroud)

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

Adr*_*agg 17

通过将ForwardedPortLocal的参数更改为:

    var port = new ForwardedPortLocal("localhost", 3306, "localhost", 3306);
Run Code Online (Sandbox Code Playgroud)

(为了明确指出我绑定的接口),并在之前添加以下代码port.Start();:

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

我注意到以下输出:

    ::1:60309
Run Code Online (Sandbox Code Playgroud)

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

    var port = new ForwardedPortLocal("127.0.0.1", 3306, "localhost", 3306);
Run Code Online (Sandbox Code Playgroud)

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