I have a service running on a particular port, but in order to make it accessible via a more memorable port as well as the normal port, I added an iptables rule that acts as a port alias:

iptables -A PREROUTING -i eth0 -p tcp -m tcp --dport 5555 -j REDIRECT --to-ports [configured port]

Perhaps I was a bit naive, but I actually started by adding a second rule in POSTROUTING that remapped the TCP source port to be the aliased port in outgoing traffic. However, it turns out I didn't need that rule at all. So, my question is: why does it work using only thing single rule?

The client makes the connection to host:alias port. Since there's no rule in iptables to remap the source port for this service's outgoing traffic, it would receive a response from the host, but with a different source port. Wouldn't this cause TCP conversation mapping issues with the client? By that I mean, the client is expecting a response from host:alias port, but would instead (theoretically) get a response from host:real port. And since the traffic wouldn't be considered "related," it shouldn't even make it through a NAT or other stateful firewall -- yet it does. Is there some magic that happens in iptables that sees the incoming prerouting rule and then automatically adjusts outgoing traffic to this rule as well?


REDIRECT target is a special case of DNAT target, used as a convenience. See related netfilter documentation, and this answer form unix StackExchange.

The DNAT targets are changing the first packet but also all future packets of the same connection, that's why one rule is enough. From man iptables (see section with target extensions, dnat):

all future packets in this connection will also be mangled

Note: targets DNAT and REDIRECT are only valid in nat table, chains PREROUTING and OUTPUT.

  • Aha! I had seen an article that compared REDIRECT to DNAT, but they seem to have left out that little tidbit when describing DNAT. Thanks for the clarification! – Chuck R Nov 2 '14 at 14:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.