In Linux IP masquerading (also known as NAT,
SNAT,
or PAT) is done by the firewall kernel modules
(iptables
).
The original change (for outgoing packets that must be masqueraded)
occurs after the routing decision, while the reverse change
(for arriving packets with the router’s destination IP address)
occurs before the routing decision.
Consider the following diagram:
Without NAT,
the request packet from the host will have source,
destination addresses of 10.1.1.2, 169.139.223.254
.
When (and if!) the web server sees this packet and replies,
it will use destination address of 10.1.1.2
.
But router B won’t know what to do with that packet!
If it forwards it at all (doubtful since this is a private
IP address) this reply packet will go to the wrong place.
With NAT,
Router A will transform the source address to
211.3.7.61
as the packet goes to the Internet.
Router B will have no trouble with the reply to that address.
When Router A receives the server's reply packet from the Internet,
it will transform the destination address back to 10.1.1.2
.
In the iptables
command below remember to specify the
interface to the outside world, not the one to your private network!
(In the diagram above, for Router A, eth0
is the interface with IP address of 211.3.7.61
.)
# iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE # echo 1 > /proc/sys/net/ipv4/ip_forward # cat /proc/net/ip_conntrack # list connections