Redirect and forward a port in Linux

There are ways to do port forwarding and redirection. We will show some examples here.

Redirect a port
When you need to redirect a port to another one on local host, it’s quite easy, here is the trick:

# iptables -t nat -I PREROUTING -p tcp --dport 1129 -j REDIRECT --to-ports 5029

It will redirect the tcp port 1129 to 5029. In other words, your services running on port 5029 is now available at 1129 as well.

Forward a port to another server
Before moving ahead, make sure you have enabled need to enable IP forwarding. IP forwarding allows your computer to act as a router, you can do that as this:

# echo 1 > /proc/sys/net/ipv4/ip_forward

Then two iptables commands are needed, in order to process the inbound and outbound traffic.
Below example show how to redirect 192.168.120.10:8080 to 172.16.172.16:3306, the two commands need to run on 192.168.120.10.

# iptables -A PREROUTING -t nat -p tcp -m tcp --dport 8080 -j DNAT -to-destination 172.16.172.16:3306
# iptables -A POSTROUTING -t nat -d 172.16.172.16 -p tcp -m tcp --dport 3306 -j SNAT --to-source 192.168.120.10

Related topics can be found here at tldp.org.

Alternatively, you can Using portfwd.
Portfwd stands for port forwarding daemon. It’s a small C++ utility which forwards incoming TCP connections and/or UDP packets to remote hosts.
Then the above usage example can be created as below:

joseph@admon$ cat portfwd.cfg
userĀ  nobody
group nobody

tcp /* TCP connections */
{
/*
* Forward localhost:8080 to 172.16.172.16:3306
*/
8080 { => 172.16.172.16:3306 }
}

joseph@admon$ ./portfwd -c portfwd.cfg

2 thoughts on “Redirect and forward a port in Linux

Leave a comment

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