Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jakoberpf/bc3382cd17776a47d418e0deb422898f to your computer and use it in GitHub Desktop.
Save jakoberpf/bc3382cd17776a47d418e0deb422898f to your computer and use it in GitHub Desktop.

redirect traffic incoming on a specific port to a different IP address / another server

2.2.2.2:4000 -> 1.1.1.1:3000

Solution

iptables -t nat -A PREROUTING -p tcp --dport 4000 -j DNAT --to-destination 1.1.1.1:3000
iptables -t nat -A POSTROUTING -p tcp -d 2.2.2.2 --dport 4000 -j SNAT --to-source 1.1.1.1
iptables -t nat -A POSTROUTING -j MASQUERADE

Explanation

Below will show you how to redirect port ip 2.2.2.2 and port 4000 on one machone to 1.1.1.1 on port 3000 of another machine.

This can be useful for firewall related reasons.

Step 1:

iptables -t nat -A PREROUTING -p tcp --dport 4000 -j DNAT --to-destination 1.1.1.1:3000
iptables -t nat -A POSTROUTING -p tcp -d 2.2.2.2 --dport 4000 -j SNAT --to-source 1.1.1.1

This will route traffic incoming on ip 2.2.2.2 and port 4000 to 1.1.1.1 on port 3000. You can put in any port or IP address you need there.

Step 2:

iptables -t nat -A POSTROUTING -j MASQUERADE

We set MASQUERADE to mask the IP address of the connecting system and use the gateway IP address instead. This is necessary for it to communicate back to the gateway, then to your client.

That is all that is required to get this to work.

Step 3:

service iptables save

This will save the changes, so they are persistent after a reboot.

Credits

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment