Redirect one port to another in Linux

You can easily redirect incoming traffic by inserting rules into PREROUTING chain of the NAT table. You can set the destination port using the REDIRECT target. In this tutorial, we will discuss how to redirect one port to another in Linux.

IPTables
IPTables

How to redirect one port to another in Linux

How to redirect TCP traffic from one port to another

To redirect the TCP traffic from one port to another, you can use the following command.

iptables -t nat -A PREROUTING -i eth0 -p tcp --dport SRC_PORT -j REDIRECT --to-port DEST_PORT

You have to replace SRC_PORT and DEST_PORT in the above command with the desired ports.

How to redirect UDP traffic from one port to another

To redirect the UDP traffic from one port to another, you can use the following command.

iptables -t nat -I PREROUTING --src SRC_IP --dst DEST_IP -p tcp --dport SRC_PORT -j REDIRECT --to-ports DEST_PORT

You have to replace SRC_PORT and DEST_PORT in the above command with the desired ports.

Verifying the iptable rules

Now verify the rule that we just added by:

iptables -t nat -Lnv

Saving iptables rules

Now given that you have verified the the rule(s) that you have added earlier in the list. Now it’s time to save them.

If you don’t want these redirection rules to persist after the next reboot then just use the following command.

iptables-save

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

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

Add a Comment

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