Sample code for 30+ languages & platforms
Zig

Check if the SSH Tunnel's Transport is Connected

See more SSH Tunnel Examples

Demonstrates the Chilkat SshTunnel.IsSshConnected method, which returns whether the SSH transport used by the tunnel is connected. It takes no arguments.

Background: A tunnel has two independent parts: the SSH transport to the server and the local listener that accepts connections to forward. This method reports only the first. The distinction matters because the listener can keep accepting local connections even after the SSH transport has dropped — those connections would then fail to forward — so a health check on a long-running tunnel should verify the SSH side explicitly.

Chilkat Zig Downloads

Zig
const std = @import("std");
const chilkat = @import("chilkat");

pub fn main(init: std.process.Init) !void {
    const alloc = init.arena.allocator();

    // Demonstrates the SshTunnel.IsSshConnected method, which returns whether the SSH transport used
    // by the tunnel is connected.  It takes no arguments.

    const tunnel = try chilkat.SshTunnel.init();
    defer tunnel.deinit();

    // The tunnel forwards accepted local connections to this destination through the SSH server.
    tunnel.setDestHostname("db.internal.example.com");
    tunnel.setDestPort(5432);

    // Connect to the SSH server.  This performs the TCP/proxy connection and SSH handshake, but
    // does not authenticate yet.
    const ssh_port = 22;
    tunnel.connect("ssh.example.com", ssh_port) catch {
        std.debug.print("{s}\n", .{try tunnel.getLastErrorText(alloc)});
        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.
    const password = "mySshPassword";

    tunnel.authenticatePw("mySshLogin", password) catch {
        std.debug.print("{s}\n", .{try tunnel.getLastErrorText(alloc)});
        return;
    };

    // Check whether the SSH transport is connected.  This is independent of the local listener
    // state -- the listener can still be accepting local connections even when this is false,
    // though those connections would fail to forward.
    if (tunnel.isSshConnected()) {
        std.debug.print("The SSH transport is connected.\n", .{});
    } else {
        std.debug.print("The SSH transport is not connected.\n", .{});
    }

    const wait_for_thread_exit = true;
    tunnel.closeTunnel(wait_for_thread_exit) catch {
        std.debug.print("{s}\n", .{try tunnel.getLastErrorText(alloc)});
        return;
    };
}