首先要打開 IP 轉發功能——在 /etc/sysctl.conf
文件中追加或修改一行:bash
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。code
使內網主機可以經過本機訪問外網:ip
$ 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 動態獲取,即上述第一句改成:table
$ iptables -t nat -A POSTROUTING -s 192.168.1.0/24 -j MASQUERADE
打印出規則表以查看,以後保存配置:class
$ iptables -t nat -L $ iptables -t filter -L
根據發行版不一樣,保存配置的方式有所區別,這裏只給出一例:配置
$ service iptables save
實現 iptables 的開機自啓:iptables
$ chkconfig --level 345 iptables on
內網機器須要手動配置網關 IP、DNS 服務器。service