美文网首页
iptables 实现简单的网关服务器

iptables 实现简单的网关服务器

作者: 字母数字或汉字 | 来源:发表于2016-11-10 02:42 被阅读624次

首先要打开 IP 转发功能——

临时生效:

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

永久生效:

/etc/sysctl.conf 文件中追加或修改一行:

net.ipv4.ip_forward = 1

使用如下命令使其立即生效:

$ sudo sysctl -p

假设本机外网 IP 为 100.100.100.100,外网段 0.0.0.0/32,内网 IP 为 192.168.1.1,内网段 192.168.1.0/24。

使内网主机能够通过本机访问外网:

$ iptables -t nat -A POSTROUTING -s 192.168.1.0/24 -j SNAT --to-source 100.100.100.100
$ iptables -t filter -A FORWARD -s 192.168.1.0/24 -j ACCEPT
$ iptables -t filter -A FORWARD -d 192.168.1.0/24 -j ACCEPT

如果本机 IP 经常变动,指定 SNAT IP 不甚方便,可以换用 MASQUERADE 动态获取,即上述第一句改为:

$ iptables -t nat -A POSTROUTING -s 192.168.1.0/24 -j MASQUERADE

打印出规则表以查看,之后保存配置:

$ iptables -t nat -L
$ iptables -t filter -L

根据发行版不同,保存配置的方式有所区别,这里只给出一例:

$ service iptables save

实现 iptables 的开机自启:

$ chkconfig --level 345 iptables on

内网机器需要手动配置网关 IP、DNS 服务器。

相关文章

网友评论

      本文标题:iptables 实现简单的网关服务器

      本文链接:https://www.haomeiwen.com/subject/ynwtpttx.html