SSH Tunneling – Add secondary address to your loopback interface HOWTO

I’m writing this one for my own reference because almost everything I do for work, is done through SSH port forwarding. If you’re not familiar with SSH port forwarding, you’ll have to read up on it elsewhere. And the reason why we use SSH port forwarding is because it is secure and powerful.

I generally set up my port forwards to run on my local computer on an arbitrary port and configure SSH to create a proxy connection to the normal port on a remote computer. Then I configure my application to connect to my local computer on the chosen arbitrary port.

For example, I would add the following in my hosts file:

sudo nano /etc/hosts
127.0.0.1 local1A.fwd
127.0.0.1 local1B.fwd
127.0.0.1 local1C.fwd

let’s say I want to forward my local requests on ports 6800, 6801, 6802 to remote servers on ports 3012, 3013, 3014. Start by modifying your ssh config:
nano .ssh/config
add the following:

host remote1A
hostname 111.111.111.111 #remote IP address goes here
user my_username #server username goes here
localforward local1A.fwd:6800 111.111.111.111:3012

host remote1B
hostname 111.111.111.111 #remote IP address goes here
user my_username #server username goes here
localforward local1B.fwd:6801 111.111.111.111:3013

host remote1C
hostname 111.111.111.111 #remote IP address goes here
user my_username #server username goes here
localforward local1C.fwd:6802 111.111.111.111:3014

You should now be able to ssh to remote machines:

ssh remote1A

and similarly for 1B and 1C.

Now, lets say you want to create another 3 local hosts and simultaneously port forward to another 3 remote machines via exact same port numbers. This is where you’ll run into problems, because you can only use one local port at a time on 127.0.0.1. The workaround it is to create secondary addresses to your loopback interface 127.0.0.2, 127.0.0.3 and so on. The command to add the secondary IP address is:

sudo ifconfig lo0 alias 127.0.0.2/32

Now you can add new set of hosts:

127.0.0.2 local2A.fwd
127.0.0.2 local2B.fwd
127.0.0.2 local2C.fwd

And use the same set of port numbers to tunnel through another set of remote servers:

host remote2A
hostname 222.222.222.222 #remote IP address goes here
user my_username #server username goes here
localforward local1A.fwd:6800 222.222.222.222:3012

host remote2B
hostname 222.222.222.222 #remote IP address goes here
user my_username #server username goes here
localforward local1B.fwd:6801 222.222.222.222:3013

host remote2C
hostname 222.222.222.222 #remote IP address goes here
user my_username #server username goes here
localforward local1C.fwd:6802 222.222.222.222:3014

Marko