Sample code for 30+ languages & platforms
C++

Connect an SSH Tunnel to the SSH Server

See more SSH Tunnel Examples

Demonstrates the Chilkat SshTunnel.Connect method, which establishes the SSH connection that carries the tunnel's traffic. The first argument is the SSH server hostname and the second is the port. It performs the connection, SSH handshake, and host-key negotiation, but does not authenticate the SSH user.

Background: Connecting establishes only the SSH transport — the encrypted channel and host-key exchange. It is the point at which the server's identity becomes known, so it is where a security-conscious client checks HostKeyFingerprint against a trusted value before handing over credentials. Authentication and BeginAccepting follow; nothing is forwarded until they do.

Chilkat C++ Downloads

C++
#include <CkSshTunnel.h>

void ChilkatSample(void)
    {
    bool success = false;

    //  Demonstrates the SshTunnel.Connect method, which establishes the SSH connection that carries
    //  tunneled traffic.  The 1st argument is the SSH server hostname and the 2nd is the port.  This
    //  performs the connection, SSH handshake, and host-key negotiation, but does not authenticate.

    CkSshTunnel tunnel;

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

    //  Connect to the SSH server.  This performs the TCP/proxy connection and SSH handshake, but
    //  does not authenticate yet.
    int sshPort = 22;
    success = tunnel.Connect("ssh.example.com",sshPort);
    if (success == false) {
        std::cout << tunnel.lastErrorText() << "\r\n";
        return;
    }

    //  Optionally verify the server's host key before authenticating.
    std::cout << "Host key fingerprint: " << tunnel.hostKeyFingerprint() << "\r\n";

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

    //  After authenticating, call BeginAccepting to start listening for local connections to forward.

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