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.