linux使用iptable做网关

2022/8/22 5:52:44

本文主要是介绍linux使用iptable做网关,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

首先在能上外网的机器上增加一块网卡

我这里两块网卡配置如下

[[email protected] ~]# cat /etc/sysconfig/network-scripts/ifcfg-eth0  外网卡

DEVICE=eth0

TYPE=Ethernet

ONBOOT=yes

NM_CONTROLLED=yes

BOOTPROTO=none

IPADDR=192.168.56.100

NETMASK=255.255.255.0

GATEWAY=192.168.56.2

DNS1=192.168.56.2

DNS2=223.5.5.5

IPV6INIT=no

USERCTL=no

 

[[email protected] ~]# cat /etc/sysconfig/network-scripts/ifcfg-eth1 内网卡

DEVICE=eth1

BOOTPROTO=none

ONBOOT=yes

NETMASK=255.255.255.0

TYPE=Ethernet

IPADDR=172.16.1.1

 

重启网络服务

service network restart

 

编辑内核配置文件,开启转发

vim /etc/sysctl.conf

使net.ipv4.ip_forward = 1

 

使内核生效

sysctl -p

清空防火墙的filter表

iptables -F

 

添加转发规则

iptables -t nat -A POSTROUTING -s 172.16.1.0/24 -j MASQUERADE  这里172.16.1.0/24与内网网段对应

 

其他机器不能上网的服务器的网卡,需要与上面的内网网卡,在同一局域网

网卡配置如下

[[email protected] ~]# cat /etc/sysconfig/network-scripts/ifcfg-eth1

DEVICE=eth0

TYPE=Ethernet

ONBOOT=yes

NM_CONTROLLED=yes

BOOTPROTO=static

IPADDR=172.16.1.10

NETMASK=255.255.255.0

GATEWAY=172.16.1.1

DNS1=192.168.56.2

DNS2=223.5.5.5

 

重启网络服务

service network restart

 

测试

[[email protected] ~]# ping 172.16.1.1 -c4

PING 172.16.1.1 (172.16.1.1) 56(84) bytes of data.

64 bytes from 172.16.1.1: icmp_seq=1 ttl=64 time=0.329 ms

64 bytes from 172.16.1.1: icmp_seq=2 ttl=64 time=0.190 ms

64 bytes from 172.16.1.1: icmp_seq=3 ttl=64 time=0.189 ms

64 bytes from 172.16.1.1: icmp_seq=4 ttl=64 time=0.182 ms

 

--- 172.16.1.1 ping statistics ---

4 packets transmitted, 4 received, 0% packet loss, time 3002ms

rtt min/avg/max/mdev = 0.182/0.222/0.329/0.063 ms

 

测试2

[[email protected] ~]# ping www.baidu.com -c4

PING www.a.shifen.com (61.135.169.121) 56(84) bytes of data.

64 bytes from 61.135.169.121: icmp_seq=1 ttl=127 time=11.7 ms

64 bytes from 61.135.169.121: icmp_seq=2 ttl=127 time=32.7 ms

64 bytes from 61.135.169.121: icmp_seq=3 ttl=127 time=9.70 ms

64 bytes from 61.135.169.121: icmp_seq=4 ttl=127 time=9.99 ms

 

--- www.a.shifen.com ping statistics ---

4 packets transmitted, 4 received, 0% packet loss, time 3015ms

rtt min/avg/max/mdev = 9.700/16.060/32.761/9.676 ms

到这里,完成!



这篇关于linux使用iptable做网关的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程