Linux 虚拟网络设备—router、tun
router
router在虚拟网络中就是路由器,实现三层通信作用。
Linux 本身开启转发功能后就是一个路由器。
# 开启转发策略
[root@public ~]# cat /proc/sys/net/ipv4/ip_forward
0
[root@public ~]# echo "net.ipv4.ip_forward=1" >> /etc/sysctl.conf
[root@public ~]# sysctl -p
net.ipv4.ip_forward = 1
[root@public ~]# cat /proc/sys/net/ipv4/ip_forward
1
[root@public ~]#
使用测试用例,模拟验证router功能,拓扑图如下:
根据拓扑图创建对应设备:
# 开启转发后,根据拓扑进行配置
[root@public ~]#
[root@public ~]# ip link add tap1 type veth peer name tap1_peer
[root@public ~]# ip link add tap2 type veth peer name tap2_peer
[root@public ~]#
[root@public ~]# ip netns add ns1
[root@public ~]# ip netns add ns2
[root@public ~]#
[root@public ~]# ip link set tap1 netns ns1
[root@public ~]# ip link set tap2 netns ns2
[root@public ~]#
[root@public ~]# ip addr add 192.168.1.1/24 dev tap1_peer
[root@public ~]# ip addr add 192.168.2.1/24 dev tap2_peer
[root@public ~]# ip netns exec ns1 ip addr add 192.168.1.100/24 dev tap1
[root@public ~]# ip netns exec ns2 ip addr add 192.168.2.100/24 dev tap2
[root@public ~]#
[root@public ~]# ip link set tap1_peer up
[root@public ~]# ip link set tap2_peer up
[root@public ~]# ip netns exec ns1 ip link set tap1 up
[root@public ~]# ip netns exec ns2 ip link set tap2 up
[root@public ~]#
[root@public ~]# ip netns exec ns1 ping 192.168.2.100
connect: Network is unreachable
[root@public ~]#
配置好ip后,发现直接通信,无法成功,检查路由信息后,发现没有去另一网段的路由,配置路由再进行测试。
[root@public ~]# ip netns exec ns1 route -nee
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface MSS Window irtt
192.168.1.0 0.0.0.0 255.255.255.0 U 0 0 0 tap1 0 0 0
[root@public ~]#
[root@public ~]# ip netns exec ns1 route add -net 192.168.2.0 netmask 255.255.255.0 gw 192.168.1.1
[root@public ~]# ip netns exec ns2 route add -net 192.168.1.0 netmask 255.255.255.0 gw 192.168.2.1
[root@public