日期:2014-05-16  浏览次数:20600 次

linux-iptables设置NAT

实验环境如下:

Fedora 17,双网卡,其中eth0用于外网,eth1用于内网。

1.配置网卡信息。

网卡信息包括:IP地址(IPADDR0),网络地址掩码(NETMASK),网关(GATEWAY0)等。这些信息均记录在文件/etc/sysconfig/netwrok-scripts/ifcfg-eth*,*表示从0起的数字,依次对应每一块网卡。例如2块网卡,则存在ifcfg-eth0/ifcfg-eth1两个文件。

文件ifcfg-eth0的内容
UUID="7221ae7b-381b-4016-a5bb-5faf97b0b8cc"
NM_CONTROLLED=yes
BOOTPROTO=none
DEVICE=eth0
ONBOOT=yes    #启动时是否启用该网卡
TYPE=Ethernet
IPADDR0=192.168.0.66    #我们可以设置多个IP
PREFIX0=24
GATEWAY0=192.168.0.1
DNS1=202.117.112.3
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=no
NAME="System eth0"
HWADDR=00:0c:29:5f:e6:eb
NETMASK=255.255.255.0
DNS2=114.114.114.114
USERCTL=no
PREFIX=24

文件ifcfg-eth1的内容
# Please read /usr/share/doc/initscripts-*/sysconfig.txt
# for the documentation of these parameters.
DNS1=202.117.112.3
DEVICE=eth1
BOOTPROTO=none
NETMASK=255.255.255.0
DNS2=114.114.114.114
TYPE=Ethernet
HWADDR=00:0c:29:5f:e6:f5
IPADDR=192.168.1.1
PREFIX=24
IPV6INIT=no
ONBOOT=yes
USERCTL=no

可以直接修改文件,也可以通过setup命令修改。

2.启用IP转发功能。

临时启用,重启失效:

echo "1" > /proc/sys/net/ipv4/ip_forward

按如下方法修改配置文件启用,一直有效。

文件/etc/sysctl.conf的内容
# Kernel sysctl configuration file
#
# For binary values, 0 is disabled, 1 is enabled.  See sysctl(8) and
# sysctl.conf(5) for more details.

# Controls IP packet forwarding
net.ipv4.ip_forward = 1  #修改这里,系统启动时读取该文件

# Controls source route verification
net.ipv4.conf.default.rp_filter = 1

# Do not accept source routing
net.ipv4.conf.default.accept_source_route = 0

# Controls the System Request debugging functionality of the kernel
kernel.sysrq = 0

# Controls whether core dumps will append the PID to the core filename.
# Useful for debugging multi-threaded applications.
kernel.core_uses_pid = 1

# Disable netfilter on bridges.
net.bridge.bridge-nf-call-ip6tables = 0
net.bridge.bridge-nf-call-iptables = 0
net.bridge.bridge-nf-call-arptables = 0


3.配置iptabls。命令如下:

iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

这样NAT服务器就配置完成了。