IPTABLES: how to do nat?

Network Address Translation, very useful for me.

You should have at leat two network interfaces.

This is an example using MASQUERADE (SNAT) dump type.

The kernel IP forwarding should be enabled before begins to setup NAT rules.

To enable on debian’s based system

# echo 1 > /proc/sys/net/ipv4/ip_forward ;(temporarily)

or add to the /etc/sysctl.conf file :

net.ipv4.ip_forward = 1 ;(for permanent)

Accepting connections through FORWARD table:

# iptables -P FORWARD ACCEPT

so the rule:

# iptables -t nat -A POSTROUTING -o (interface that has the internet connection) -j MASQUERADE

Note: is very important to have two different network ranges like and know what would be the gateway on the clients.
eth0 > dhcp from ISP
eth1 > (NAT range)

For permanent effect:

add to /etc/rc.local script this line:

/sbin/iptables -t nat -A POSTROUTING -o (interface with internet) -j MASQUERADE


note: you can set up a DHCP server and make the job easier.

ip > (into NAT range) ; this address could be different
Subnet Mask > ; this address could be different
Gateway > ; Linux nat interface (in this case eth1 address)

DNS servers > you can set public DNS address like openDNS or internal ones. On the Linux system machine with NAT rules type:

# cat /etc/resolv.conf

and put the Linux’s system DNS. (may be a router with another NAT range with a DNS server configured)

Tip! You can make restrinctions to any service on the network introducing INPUT rules like into FORWARD table with the prefix:

# iptables -A FORWARD ...


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s