Sample code for 30+ languages & platforms
C++

SSH Tunnel Timeouts and IP Preference

See more SSH Tunnel Examples

Demonstrates the ConnectTimeoutMs, IdleTimeoutMs, and PreferIpv6 properties, which govern how long the tunnel waits to connect and to transfer data, and which IP version it prefers.

Background: ConnectTimeoutMs bounds how long a connection attempt blocks — important so an unreachable server fails promptly instead of hanging — while IdleTimeoutMs guards against a stalled transfer holding a connection open indefinitely. PreferIpv6 only matters when a hostname resolves to both address families, choosing which to try first; the default prefers IPv4.

Chilkat C++ Downloads

C++
#include <CkSshTunnel.h>

void ChilkatSample(void)
    {
    bool success = false;

    //  Demonstrates the SshTunnel connection-behavior properties ConnectTimeoutMs, IdleTimeoutMs, and
    //  PreferIpv6.

    CkSshTunnel tunnel;

    //  Maximum time to establish the SSH connection (default 30000 ms).
    tunnel.put_ConnectTimeoutMs(10000);

    //  Stall timeout for tunnel data-transfer operations (default 30000 ms).
    tunnel.put_IdleTimeoutMs(15000);

    //  When a hostname resolves to both IPv4 and IPv6, prefer IPv6.  The default (false) prefers IPv4.
    tunnel.put_PreferIpv6(true);

    tunnel.put_DestHostname("db.internal.example.com");
    tunnel.put_DestPort(5432);

    int sshPort = 22;
    success = tunnel.Connect("ssh.example.com",sshPort);
    if (success == false) {
        std::cout << tunnel.lastErrorText() << "\r\n";
        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 char *password = "mySshPassword";

    success = tunnel.AuthenticatePw("mySshLogin",password);
    if (success == false) {
        std::cout << tunnel.lastErrorText() << "\r\n";
        return;
    }

    int listenPort = 1080;
    success = tunnel.BeginAccepting(listenPort);
    if (success == false) {
        std::cout << tunnel.lastErrorText() << "\r\n";
        return;
    }

    std::cout << "Tunnel established." << "\r\n";

    bool waitForThreadExit = true;
    success = tunnel.CloseTunnel(waitForThreadExit);
    if (success == false) {
        std::cout << tunnel.lastErrorText() << "\r\n";
        return;
    }
    }