Sample code for 30+ languages & platforms
Android™

Route Socket Connections through an SSH Object

See more Socket/SSL/TLS Examples

Demonstrates Socket.UseSsh, which configures a socket to route subsequent Connect calls through an already connected and authenticated Ssh object using SSH port forwarding.

Background. After UseSsh, the destination host and port passed to Connect are reached through the SSH tunnel rather than by a direct TCP connection. This is one of several SSH-tunneling approaches the Socket class supports.

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;

    CkSsh ssh = new CkSsh();

    //  Connect and authenticate a standalone SSH object.
    success = ssh.Connect("ssh.example.com",22);
    if (success == false) {
        Log.i(TAG, ssh.lastErrorText());
        return;
        }

    //  The SSH password should come from a secure source rather than being hard-coded.
    String sshPassword = "mySshPassword";
    success = ssh.AuthenticatePw("sshUser",sshPassword);
    if (success == false) {
        Log.i(TAG, ssh.lastErrorText());
        return;
        }

    CkSocket socket = new CkSocket();

    //  Route subsequent Connect calls through the already connected and authenticated SSH object.  The
    //  destination is reached by SSH port forwarding rather than by a direct TCP connection.
    success = socket.UseSsh(ssh);
    if (success == false) {
        Log.i(TAG, socket.lastErrorText());
        return;
        }

    //  Connect to the destination through the SSH tunnel.
    boolean bTls = false;
    int maxWaitMs = 5000;
    success = socket.Connect("db.internal",5432,bTls,maxWaitMs);
    if (success == false) {
        Log.i(TAG, socket.lastErrorText());
        return;
        }

    Log.i(TAG, "Connected to the destination through the SSH tunnel.");

  }

  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."
  }
}