Configuring Port Forwarding

In our Working with the Client API article we walk you through creating a client connection with the Maverick NG API. If you just want the basic template for creating a client you can also take a look at our Quick Start article that provides just the code needed to create a client SSH connection. Refer to one of these articles for your initial connection. In this article we will show you how to extend the basic template to configure port forwarding.

The first requirement is to enable forwarding on the ForwardingPolicy object that is part of the SshContext.

     sshContext.getForwardingPolicy().allowForwarding();

Once you have connected the client, in your ConnectionStateListener you can then configure the forwarding you require in response to the connected event. First you must get a reference to the ConnectionProtocolClient. This provides the various services available on the SSH connection.

     ConnectionProtocolClient client = 
(ConnectionProtocolClient) con.getConnectionProtocol();

To configure local forwarding

     try {
          client.startLocalForwarding("127.0.0.1", 8081, "127.0.0.1", 80);
     } catch(UnauthorizedException | SshException e) {
	// Handle error. Do not throw an exception.
     }

Or to configure remote forwarding

try {
	  client.startRemoteForwarding("127.0.0.1", 8080, "127.0.0.1", 80); 
     } catch(UnauthorizedException | SshExceptione) { 
// Handle error. Do not throw an exception.
}

 

Gateway Forwarding 

If you want port forwards to be accessed from remote machines you need to enable gateway forwarding. The initial forwarding configuration will only allow port forwarding listeners to be accessed from the loopback address on localhost.

To enable other clients to access the forwarding use

     sshContext.getForwardingPolicy().allowGatewayForwarding();

This will allow you to open up local forwarding using the wildcard socket address

     client.startLocalForwarding("::", 8081, "127.0.0.1", 80);

 

Have more questions? Submit a request

0 Comments

Please sign in to leave a comment.