This is also helpful when dealing with applications that need access to a port number less than 1024, that should not be run as root.
iptables -t nat -A PREROUTING -p tcp --dport 5600 -j REDIRECT --to-ports 25
What this does:
-A
), which means to add the rule at the bottom of the list.-p tcp
)--dport
) is 5600
- this is the port that the client is trying to access on your server.-j
) to the REDIRECT
action. This is the action that is taken when the rule matches.25
on the server.By changing the protocol to either tcp or udp or by adjusting the dport number and the to-ports number, you can redirect any port incoming to any listening port on the server. Just remember that the dport is the port the client machine is trying to connect to (the port they configure in the mail client, for example).
We can take this further. Say for example you have a website. You don't have a load balancer or a firewall set up, but you want to split off your email traffic to a second server to reduce strain on your web server. Essentially, you want to take incoming port 25 and redirect it ... to ANOTHER SERVER. With iptables, you can make this work:
iptables -t nat -A PREROUTING -p tcp -d 200.200.200.200 --dport 25 -j DNAT --to-destination 10.10.10.10:25
What this does:
-d
) IP address. This is not needed, but if you want to limit the email redirection to a single address, this is how you can do it.DNAT
, which stands for destination nat.to-destination
This forwards all traffic on port 25 to an internal IP address.
Now, say you want to redirect from a different incoming port to a port on another server:
iptables -t nat -A PREROUTING -p tcp --dport 5600 -j DNAT --to-destination 10.10.10.10:25
iptables -t nat -A POSTROUTING -p tcp --dport 25 -j MASQUERADE
In this example, the incoming port is different, so we need to change it back to the standard port on the way back out through the primary server.