Sample code for 30+ languages & platforms
Swift

Get an SSH Tunnel's Current State (Diagnostics)

See more SSH Tunnel Examples

Demonstrates the Chilkat SshTunnel.GetCurrentState method, which returns an XML snapshot describing the tunnel manager, SSH channels, and current tunnel clients. It takes no arguments and is intended for diagnostics and monitoring.

Background: Because the tunnel forwards traffic on a background thread, there is no natural place in your code to observe what it is doing at a given moment. GetCurrentState provides that visibility — byte counts, active channels, and connected clients — as structured XML suited to logging or a monitoring dashboard. It is a read-only snapshot and does not affect the tunnel.

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    //  Demonstrates the SshTunnel.GetCurrentState method, which returns an XML snapshot describing the
    //  tunnel manager, SSH channels, and current tunnel clients.  It takes no arguments and is
    //  intended for diagnostics and monitoring.

    let tunnel = CkoSshTunnel()!

    //  The tunnel forwards accepted local connections to this destination through the SSH server.
    tunnel.destHostname = "db.internal.example.com"
    tunnel.destPort = 5432

    //  Connect to the SSH server.  This performs the TCP/proxy connection and SSH handshake, but
    //  does not authenticate yet.
    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
    }

    //  Begin accepting so there is live tunnel state to inspect.
    var listenPort: Int = 1080
    success = tunnel.beginAccepting(listenPort: listenPort)
    if success == false {
        print("\(tunnel.lastErrorText!)")
        return
    }

    //  Get a diagnostic snapshot of the tunnel's current state as XML.
    var stateXml: String? = tunnel.getCurrentState()
    if tunnel.lastMethodSuccess == false {
        print("\(tunnel.lastErrorText!)")
        return
    }

    print("\(stateXml!)")

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


}