Sample code for 30+ languages & platforms
Zig

SSH Tunnel Static (Fixed-Destination) Port Forwarding

See more SSH Tunnel Examples

Demonstrates fixed-destination port forwarding with the DestHostname, DestPort, ListenBindIpAddress, and ListenPort properties. Every local connection accepted by the listener is forwarded to the same fixed destination through the SSH server.

Background: This is the classic ssh -L scenario: expose a single remote service — a database, an internal web app — at a local port. Binding the listener to 127.0.0.1 keeps the tunnel private to the local machine, whereas 0.0.0.0 would let other hosts route through it. Passing 0 to BeginAccepting lets the OS pick a free port, which ListenPort then reports — handy when a fixed port might already be in use.

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 fixed-destination (static) port forwarding with the SshTunnel properties
    // DestHostname, DestPort, ListenBindIpAddress, and ListenPort.
    //
    // Every local connection accepted by the listener is forwarded to the same fixed destination
    // through the SSH server.

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

    // The fixed destination that accepted connections are forwarded to.
    tunnel.setDestHostname("db.internal.example.com");
    tunnel.setDestPort(5432);

    // Bind the listener to loopback so only local processes can use the tunnel.  Use "0.0.0.0" to
    // accept connections from other machines (less secure).
    tunnel.setListenBindIpAddress("127.0.0.1");

    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;
    };

    // Pass 0 to let the operating system choose an available port.  After BeginAccepting succeeds,
    // ListenPort contains the actual port that was bound.
    tunnel.beginAccepting(0) catch {
        std.debug.print("{s}\n", .{try tunnel.getLastErrorText(alloc)});
        return;
    };

    std.debug.print("Listening on 127.0.0.1 port {d}\n", .{tunnel.getListenPort()});

    // Applications now connect to 127.0.0.1:ListenPort as if it were the database server.

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