Sample code for 30+ languages & platforms
Swift

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

Swift

func chilkatTest() {
    var success: Bool = false

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

    let tunnel = CkoSshTunnel()!

    //  Maximum time to establish the SSH connection (default 30000 ms).
    tunnel.connectTimeoutMs = 10000

    //  Stall timeout for tunnel data-transfer operations (default 30000 ms).
    tunnel.idleTimeoutMs = 15000

    //  When a hostname resolves to both IPv4 and IPv6, prefer IPv6.  The default (false) prefers IPv4.
    tunnel.preferIpv6 = true

    tunnel.destHostname = "db.internal.example.com"
    tunnel.destPort = 5432

    var sshPort: Int = 22
    success = tunnel.connect(hostname: "ssh.example.com", port: sshPort)
    if success == false {
        print("\(tunnel.lastErrorText!)")
        return
    }

    //  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.
    var password: String? = "mySshPassword"

    success = tunnel.authenticatePw(login: "mySshLogin", password: password)
    if success == false {
        print("\(tunnel.lastErrorText!)")
        return
    }

    var listenPort: Int = 1080
    success = tunnel.beginAccepting(listenPort: listenPort)
    if success == false {
        print("\(tunnel.lastErrorText!)")
        return
    }

    print("Tunnel established.")

    var waitForThreadExit: Bool = true
    success = tunnel.closeTunnel(waitForThreads: waitForThreadExit)
    if success == false {
        print("\(tunnel.lastErrorText!)")
        return
    }


}