Sample code for 30+ languages & platforms
B4X

Route Socket Connections through an SSH Object

See more Socket/SSL/TLS Examples

Demonstrates Socket.UseSsh, which configures a socket to route subsequent Connect calls through an already connected and authenticated Ssh object using SSH port forwarding.

Background. After UseSsh, the destination host and port passed to Connect are reached through the SSH tunnel rather than by a direct TCP connection. This is one of several SSH-tunneling approaches the Socket class supports.

Chilkat B4X Downloads

B4X
Dim success As Boolean = False

Dim ssh As ChilkatSsh
ssh.Initialize("ssh")

'  Connect and authenticate a standalone SSH object.
success = ssh.Connect("ssh.example.com", 22)
If success = False Then
    Log(ssh.LastErrorText)
    Return
End If


'  The SSH password should come from a secure source rather than being hard-coded.
Dim sshPassword As String = "mySshPassword"
success = ssh.AuthenticatePw("sshUser", sshPassword)
If success = False Then
    Log(ssh.LastErrorText)
    Return
End If


Dim socket As ChilkatSocket
socket.Initialize("socket")

'  Route subsequent Connect calls through the already connected and authenticated SSH object.  The
'  destination is reached by SSH port forwarding rather than by a direct TCP connection.
success = socket.UseSsh(ssh)
If success = False Then
    Log(socket.LastErrorText)
    Return
End If


'  Connect to the destination through the SSH tunnel.
Dim bTls As Boolean = False
Dim maxWaitMs As Int = 5000
success = socket.Connect("db.internal", 5432, bTls, maxWaitMs)
If success = False Then
    Log(socket.LastErrorText)
    Return
End If

Log("Connected to the destination through the SSH tunnel.")