Redirect one port to another port using iptables

You can easily redirect incoming traffic by inserting rules into PREROUTING chain of the nat table. You can set destination port using the REDIRECT target.

IPTables
IPTables

Following is the procedure:
Use the following for redirecting TCP traffic from one SRC_PORT to DEST_PORT:
[code lang=”bash”]
iptables -t nat -A PREROUTING -i eth0 -p tcp –dport SRC_PORT -j REDIRECT –to-port DEST_PORT
[/code]

Use the following for redirecting UDP traffic from one SRC_PORT to DEST_PORT:
[code lang=”bash”]iptables -t nat -A PREROUTING -i eth0 -p udp –dport SRC_PORT -j REDIRECT –to-port DEST_PORT[/code]

Use the following for redirecting TCP traffic from one IP:SRC_PORT to another IP:DEST_PORT:
[code lang=”bash”]iptables -t nat -I PREROUTING –src SRC_IP –dst DEST_IP -p tcp –dport SRC_PORT -j REDIRECT –to-ports DEST_PORT[/code]

Now verify the rule that we just added by:
[code lang=”bash”]iptables -t nat -Lnv[/code]

You can see the the rule(s) that you have added earlier in the list. Now time to save the rules.

Here, if you just want these redirection rules to persist only for current boot then just run the following command.

[code lang=”bash”]iptables-save [/code]

If you want the redirection rules to persist even after the reboot then, please follow the procedure below: (Ubuntu 14.04)

[code lang=”bash”]
sudo iptables-save > /etc/network/interfaces.d/iptables.rules
echo "post-up iptables-restore < /etc/network/interfaces.d/iptables.rules" > /etc/network/interfaces.d/eth0.cfg
[/code]

Add a Comment

Your email address will not be published. Required fields are marked *