Sample code for 30+ languages & platforms
Swift

SSH Tunnel Through an Outbound SOCKS Proxy

See more SSH Tunnel Examples

Demonstrates reaching the SSH server through an outbound SOCKS proxy using the SocksVersion, SocksHostname, SocksPort, SocksUsername, and SocksPassword properties.

Background: This is the reverse direction from dynamic forwarding: here a SOCKS proxy is used to reach the SSH server, for networks where outbound connections must pass through one. SocksVersion is the switch — 0 means no SOCKS, while 4 or 5 selects the protocol. SOCKS5 supports username/password authentication and remote DNS; SOCKS4 supports only a username.

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    //  Demonstrates reaching the SSH server through an outbound SOCKS proxy using the SshTunnel
    //  properties SocksVersion, SocksHostname, SocksPort, SocksUsername, and SocksPassword.

    let tunnel = CkoSshTunnel()!

    //  Set SocksVersion to 4 or 5 to route the outbound connection to the SSH server through a SOCKS
    //  proxy.  A value of 0 (the default) means no SOCKS proxy.
    tunnel.socksVersion = 5
    tunnel.socksHostname = "socks.example.com"
    tunnel.socksPort = 1080

    //  SOCKS4 supports only a username; SOCKS5 supports username and password.
    tunnel.socksUsername = "myProxyLogin"
    tunnel.socksPassword = "myProxyPassword"

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

    //  Connect to the SSH server through the SOCKS proxy configured above.
    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 through the SOCKS proxy.")

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


}