Skip to content

SSH.TCPTunnel

Andrew Lambert edited this page Mar 25, 2023 · 25 revisions

SSH.TCPTunnel

Class Declaration

 Protected Class TCPTunnel
 Inherits SSH.Channel

Remarks

This class represents a TCP/IP tunnel between your app and a third party using the SSH server as an intermediary. Traffic between your app and the SSH server is protected by SSH's encryption, however traffic between the SSH server and the third party is not.

To initiate an outbound connection from your app call the Connect() method. To wait for a single inbound connection from a third-party call the Listen() method; refer to the TCPListener class if you need to accept multiple connections.

Connect() Example

This example forwards an HTTP request through the SSH server to www.example.com:80.

  Dim session As SSH.Session = SSH.Connect("ssh.example.com", 22, "username", "password")
  Dim tunnel As New SSH.TCPTunnel(session)
  tunnel.RemoteAddress = "www.example.com" ' ssh server will connect to this third party
  tunnel.RemotePort = 80 ' ssh server will connect to this TCP port on the third party
  If Not tunnel.Connect() Then MsgBox("Unable to open tunnel.")

  ' write to the tunnel
  tunnel.Write( _
     "GET / HTTP/1.0" + EndOfLine.Windows + _
     "Host: www.example.com" + EndOfLine.Windows + _
     "Connection: close" + EndOfLine.Windows + EndOfLine.Windows)
  ' Connection: close instructs the web server to close the TCP connection
  ' after all data is sent. This causes TCPTunnel.EOF to be True. Note that
  ' many TCP based protocols keep the connection alive through multiple requests
  
  ' read from the tunnel
  Dim output As String
  Do Until tunnel.EOF
    If tunnel.PollReadable() Then
      output = output + tunnel.Read(tunnel.BytesReadable)
    End If
  Loop

Listen() Example

This example instructs the SSH server to wait for a connection on port 8080. If a connection is received we read from it until EOF and just echo back anything that was sent.

  Dim session As SSH.Session = SSH.Connect("ssh.example.com", 22, "username", "password")
  Dim tunnel As New SSH.TCPTunnel(session)
  tunnel.RemotePort = 8080  ' ssh server will listen on TCP port 8080
  tunnel.RemoteAddress = "" ' ssh server will listen on all of its TCP interfaces
  tunnel.Listen()
  
  Do Until tunnel.IsConnected Or tunnel.EOF
    Call tunnel.Poll()
  Loop 
  
  If tunnel.IsConnected Then
    Do Until tunnel.EOF
      If tunnel.PollReadable Then
        request = request + tunnel.Read(tunnel.BytesReadable)
        Exit Do ' pretend for the sake of example that everything arrived at once
      End If
    Loop
    
    tunnel.Write(request) ' just echo it back for this example
    tunnel.Close()
  End If

Event definitions

Methods

Properties

See also

Clone this wiki locally