Configure NAT On Linux With IPTABLES

12 May 2012

Tested On

OS: CentOS 6.2 i386
iptables version: v1.4.7
Hardware: Virtual Machine (VirtualBox 4.1.14)


Network Address Translation (NAT) is a technology that translate private addresses to public and vice versa. In this guide I will show how to implement the main types of NAT using linux and iptables.

Network Address Port Translation (NAPT)/Port Address Translation (PAT)

NAPT is the most common type of NAT. This type of NAT on a traditional outbound transaction change the source IP and the source port, and because it change also the source port multiple devices can share the same IP simultaneously.

iptables -t nat -A POSTROUTING -o eth0 -j SNAT --to-source
-t nat - Use NAT table of iptables
-A POSTROUTING - Append the rule to POSTROUTING chain on the NAT table
-o interface - Specify on which outgoing interface apply this rule
-j SNAT - Change the source address
--to-source - Source addresses list to change the original source address
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

Traditional/Outbound NAT

Traditional NAT share public IP addresses with local devices that use private IP addresses.

Traditional NAT is implemented in iptables like NAPT with multiple source IP addresses.

iptables -t nat -A POSTROUTING -o eth0 -j SNAT --to-source

Bidirectional/Inbound NAT

Bidirectional NAT is used when a device from the outside network needs to initiate a session with server on the inside network.

iptables -t nat -A PREROUTING -i eth0 -j DNAT --to-destination
iptables -t nat -A POSTROUTING -d -j MASQUERADE
-i interface - Name of an interface via a packet was received
--to-destination local_ip_address - IP address of a local server
iptables -t nat -A PREROUTING -d -j DNAT --to-destination
iptables -t nat -A PREROUTING -p tcp -d --dport 80 -j DNAT --to-destination