iptables做nat网络地址转换

iptables做nat网络地址转换。

0. 权威文档

http://www.netfilter.org/documentation/HOWTO/NAT-HOWTO-6.html
e文好的直接跳过本文。

1. Source NAT

在POSTROUTING链里面定义,用-j SNAT,--to-source 省略成--to,ip ,ip段,地址段

## Change source addresses to 1.2.3.4.
# iptables -t nat -A POSTROUTING -o eth0 -j SNAT --to 1.2.3.4
## Change source addresses to 1.2.3.4, 1.2.3.5 or 1.2.3.6
# iptables -t nat -A POSTROUTING -o eth0 -j SNAT --to 1.2.3.4-1.2.3.6
## Change source addresses to 1.2.3.4, ports 1-1023
# iptables -t nat -A POSTROUTING -p tcp -o eth0 -j SNAT --to 1.2.3.4:1-1023

Masquerading

其实是snat中的一种特殊情况,用在来源动态的地址。而且不能指定source address,只能指定来源端口(interface).
But more importantly, if the link goes down, the connections (which are now lost anyway) are forgotten, meaning fewer glitches when connection comes back up with a new IP address.

## Masquerade everything out ppp0.
# iptables -t nat -A POSTROUTING -o ppp0 -j MASQUERADE

2. Destination NAT

定义在PREROUTING链。用-j DNAT,--to-destination指定ip,ip段,端口段。

## Change destination addresses to 5.6.7.8
# iptables -t nat -A PREROUTING -i eth0 -j DNAT --to 5.6.7.8
## Change destination addresses to 5.6.7.8, 5.6.7.9 or 5.6.7.10.
# iptables -t nat -A PREROUTING -i eth0 -j DNAT --to 5.6.7.8-5.6.7.10
## Change destination addresses of web traffic to 5.6.7.8, port 8080.
# iptables -t nat -A PREROUTING -p tcp --dport 80 -i eth0 -j DNAT --to 5.6.7.8:8080

Redirection

Redirection是dnat一种特殊情况,将数据库转发到相同interface的另一个端口。

## Send incoming port-80 web traffic to our squid (transparent) proxy
# iptables -t nat -A PREROUTING -i eth1 -p tcp --dport 80 \
        -j REDIRECT --to-port 3128

squid做透明代理的时候就用这条规则。

posted @ 2015-10-13 10:32  过去的我  阅读(892)  评论(0编辑  收藏  举报