Sample code for 30+ languages & platforms
PureBasic

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 PureBasic Downloads

PureBasic
IncludeFile "CkSshTunnel.pb"

Procedure ChilkatExample()

    success.i = 0

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

    tunnel.i = CkSshTunnel::ckCreate()
    If tunnel.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    ;  Maximum time to establish the SSH connection (default 30000 ms).
    CkSshTunnel::setCkConnectTimeoutMs(tunnel, 10000)

    ;  Stall timeout for tunnel data-transfer operations (default 30000 ms).
    CkSshTunnel::setCkIdleTimeoutMs(tunnel, 15000)

    ;  When a hostname resolves to both IPv4 and IPv6, prefer IPv6.  The default (0) prefers IPv4.
    CkSshTunnel::setCkPreferIpv6(tunnel, 1)

    CkSshTunnel::setCkDestHostname(tunnel, "db.internal.example.com")
    CkSshTunnel::setCkDestPort(tunnel, 5432)

    sshPort.i = 22
    success = CkSshTunnel::ckConnect(tunnel,"ssh.example.com",sshPort)
    If success = 0
        Debug CkSshTunnel::ckLastErrorText(tunnel)
        CkSshTunnel::ckDispose(tunnel)
        ProcedureReturn
    EndIf

    ;  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.
    password.s = "mySshPassword"

    success = CkSshTunnel::ckAuthenticatePw(tunnel,"mySshLogin",password)
    If success = 0
        Debug CkSshTunnel::ckLastErrorText(tunnel)
        CkSshTunnel::ckDispose(tunnel)
        ProcedureReturn
    EndIf

    listenPort.i = 1080
    success = CkSshTunnel::ckBeginAccepting(tunnel,listenPort)
    If success = 0
        Debug CkSshTunnel::ckLastErrorText(tunnel)
        CkSshTunnel::ckDispose(tunnel)
        ProcedureReturn
    EndIf

    Debug "Tunnel established."

    waitForThreadExit.i = 1
    success = CkSshTunnel::ckCloseTunnel(tunnel,waitForThreadExit)
    If success = 0
        Debug CkSshTunnel::ckLastErrorText(tunnel)
        CkSshTunnel::ckDispose(tunnel)
        ProcedureReturn
    EndIf



    CkSshTunnel::ckDispose(tunnel)


    ProcedureReturn
EndProcedure