Swift
Swift
Close an SSH Tunnel (CloseTunnel)
See more SSH Tunnel Examples
Demonstrates the Chilkat SshTunnel.CloseTunnel method, which disconnects active tunnel clients and stops the tunnel-manager thread. The only argument (waitForThreads) selects whether to wait for the worker threads to exit.
Background: This is the full shutdown — it stops the listener, disconnects clients, and ends the background threads, so it is what you call when the tunnel is no longer needed. Passing
true for waitForThreads makes the call block until the workers have actually exited, which matters before the program terminates or reuses the object; if a worker fails to stop, the method returns false and LastErrorText explains why.Chilkat Swift Downloads
func chilkatTest() {
var success: Bool = false
// Demonstrates the SshTunnel.CloseTunnel method, which disconnects active tunnel clients and stops
// the tunnel-manager thread. The only argument (waitForThreads) selects whether to wait for the
// worker threads to exit.
let tunnel = CkoSshTunnel()!
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
}
// ... the tunnel runs ...
// Shut everything down: disconnect clients and stop the tunnel-manager thread. With
// waitForThreads true, the method waits for the worker threads to exit.
var waitForThreads: Bool = true
success = tunnel.closeTunnel(waitForThreads: waitForThreads)
if success == false {
print("\(tunnel.lastErrorText!)")
return
}
print("Tunnel closed.")
}