Sample code for 30+ languages & platforms
Android™

Open a Forwarded Channel through an SSH Tunnel

See more Socket/SSL/TLS Examples

Demonstrates Socket.SshNewChannel, which opens a port-forwarded channel through an authenticated SSH tunnel to a destination host and port, populating a Socket with the connected channel.

Background. Set the ssl argument to true to establish TLS to the destination inside the SSH tunnel. The returned channel socket is then used to send and receive with the destination.

Chilkat Android™ Downloads

Android™
// Important: Don't forget to include the call to System.loadLibrary
// as shown at the bottom of this code sample.
package com.test;

import android.app.Activity;
import com.chilkatsoft.*;

import android.widget.TextView;
import android.os.Bundle;

public class SimpleActivity extends Activity {

  private static final String TAG = "Chilkat";

  // Called when the activity is first created.
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    boolean success = false;

    CkSocket socket = new CkSocket();

    //  Connect to the SSH server and initialize an SSH tunneling session.  Port 22 is conventional but
    //  not required.
    success = socket.SshOpenTunnel("ssh.example.com",22);
    if (success == false) {
        Log.i(TAG, socket.lastErrorText());
        return;
        }

    //  Authenticate the SSH session before opening forwarded channels.
    //  The SSH password should come from a secure source rather than being hard-coded.
    String sshPassword = "mySshPassword";
    success = socket.SshAuthenticatePw("sshUser",sshPassword);
    if (success == false) {
        Log.i(TAG, socket.lastErrorText());
        return;
        }

    //  Open a port-forwarded channel through the authenticated SSH tunnel to the destination host and
    //  port, populating a Socket with the connected channel.  Set the 3rd argument to true to establish
    //  TLS to the destination inside the tunnel.
    boolean bTls = false;
    int maxWaitMs = 20000;
    CkSocket channel = new CkSocket();
    success = socket.SshNewChannel("db.internal",5432,bTls,maxWaitMs,channel);
    if (success == false) {
        Log.i(TAG, socket.lastErrorText());
        return;
        }

    //  Use the channel socket to send and receive with the destination through the tunnel.
    Log.i(TAG, "Forwarded channel opened to the destination.");

  }

  static {
      System.loadLibrary("chilkat");

      // Note: If the incorrect library name is passed to System.loadLibrary,
      // then you will see the following error message at application startup:
      //"The application <your-application-name> has stopped unexpectedly. Please try again."
  }
}