Port forwarding with iptables

If you ever want to try port forwarding with iptables, here is a quick example of forwarding a public port (45000) – public network to a private port (22) – ssh – private network:

$ iptables -t nat -A PREROUTING -p tcp --dport 45000 -j DNAT --to-destination 192.168.1.200:22
$ iptables -t nat -A POSTROUTING -j MASQUERADE

If this is not working, check if your system has enabled ip forwarding. If not, execute this in your terminal:

$ sysctl net.ipv4.ip_forward=1

* The above command might not work if you are on a VPS.

Avoid ssh connection timeout

One way to avoid ssh connection timeout, is to use your ssh config file:

$ vim ~/.ssh/config

Add the following lines:

Host myhost
  HostName myhost.tld
  ServerAliveInterval 60
  Port 22
  User myusername

Or, if you want to set the keep alive for all hosts:

Host *
  ServerAliveInterval 60

Tip: now you can connect like this:

$ ssh myhost