Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
380 views
in Technique[技术] by (71.8m points)

c# - Creating a forwarded port within an SSH tunnel

I'm attempting to use SSH.NET to create a tunnel from localhost:3306 to port 3306 on a remote machine:

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

When the breakpoint is hit, client.IsConnected is returning true, 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

    ::1:60309

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("127.0.0.1", 3306, "localhost", 3306);

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...