Linux – How to Forward a Port from One Machine to Another?

linuxport-forwarding

Consider the following situation:

At my home, I have a router (which is connected to internet), server (S) and my main machine (M). S is reachable from the internet (it has static IP), and it is up 24/7, while M is not.

Sometimes, I want to make some app (which listens on some port on M, for example 8888) accessible from outer internet.

For that, I wanted to set up some port on S (2222) to forward to M's port 8888, so that anybody accessing S:2222 would feel like he was accessing M:8888.

I tried to use ssh port forwarding, my best attempt was as follows:

ssh -L 2222:M:8888 -N M

But that only allows me to access 2222 port from server itself, not from other machines.

Is there some way to do it properly? Preferably, I'd like it to be a simple command, which I would be able to start and shut down with ^C when I don't need that forwarding anymore.

Best Answer

Yes, this is called GatewayPorts in SSH. An excerpt from ssh_config(5):

GatewayPorts
        Specifies whether remote hosts are allowed to connect to local
        forwarded ports.  By default, ssh(1) binds local port forwardings
        to the loopback address.  This prevents other remote hosts from
        connecting to forwarded ports.  GatewayPorts can be used to spec‐
        ify that ssh should bind local port forwardings to the wildcard
        address, thus allowing remote hosts to connect to forwarded
        ports.  The argument must be “yes” or “no”.  The default is “no”.

And you can use localhost instead of M in the forwarding, as you're forwarding to the same machine as you're SSH-ing to -- if I understand your question correctly.

So, the command will become this:

ssh -L 2222:localhost:8888 -N -o GatewayPorts=yes hostname-of-M

and will look like this in netstat -nltp:

tcp        0      0    0.0.0.0:2222   0.0.0.0:*  LISTEN  5113/ssh

Now anyone accessing this machine at port 2222 TCP will actually talk to localhost:8888 as seen in machine M. Note that this is not the same as plain forwarding to port 8888 of M.

Related Question