Sample code for 30+ languages & platforms
Tcl

SSH Tunnel Timeouts and IP Preference

See more SSH Tunnel Examples

Demonstrates the ConnectTimeoutMs, IdleTimeoutMs, and PreferIpv6 properties, which govern how long the tunnel waits to connect and to transfer data, and which IP version it prefers.

Background: ConnectTimeoutMs bounds how long a connection attempt blocks — important so an unreachable server fails promptly instead of hanging — while IdleTimeoutMs guards against a stalled transfer holding a connection open indefinitely. PreferIpv6 only matters when a hostname resolves to both address families, choosing which to try first; the default prefers IPv4.

Chilkat Tcl Downloads

Tcl

load ./chilkat.dll

set success 0

#  Demonstrates the SshTunnel connection-behavior properties ConnectTimeoutMs, IdleTimeoutMs, and
#  PreferIpv6.

set tunnel [new_CkSshTunnel]

#  Maximum time to establish the SSH connection (default 30000 ms).
CkSshTunnel_put_ConnectTimeoutMs $tunnel 10000

#  Stall timeout for tunnel data-transfer operations (default 30000 ms).
CkSshTunnel_put_IdleTimeoutMs $tunnel 15000

#  When a hostname resolves to both IPv4 and IPv6, prefer IPv6.  The default (0) prefers IPv4.
CkSshTunnel_put_PreferIpv6 $tunnel 1

CkSshTunnel_put_DestHostname $tunnel "db.internal.example.com"
CkSshTunnel_put_DestPort $tunnel 5432

set sshPort 22
set success [CkSshTunnel_Connect $tunnel "ssh.example.com" $sshPort]
if {$success == 0} then {
    puts [CkSshTunnel_lastErrorText $tunnel]
    delete_CkSshTunnel $tunnel
    exit
}

#  Normally you would not hard-code the password in source.  You should instead obtain it
#  from an interactive prompt, environment variable, or a secrets vault.
set password "mySshPassword"

set success [CkSshTunnel_AuthenticatePw $tunnel "mySshLogin" $password]
if {$success == 0} then {
    puts [CkSshTunnel_lastErrorText $tunnel]
    delete_CkSshTunnel $tunnel
    exit
}

set listenPort 1080
set success [CkSshTunnel_BeginAccepting $tunnel $listenPort]
if {$success == 0} then {
    puts [CkSshTunnel_lastErrorText $tunnel]
    delete_CkSshTunnel $tunnel
    exit
}

puts "Tunnel established."

set waitForThreadExit 1
set success [CkSshTunnel_CloseTunnel $tunnel $waitForThreadExit]
if {$success == 0} then {
    puts [CkSshTunnel_lastErrorText $tunnel]
    delete_CkSshTunnel $tunnel
    exit
}


delete_CkSshTunnel $tunnel