通过一对虚拟网卡测试两个网络名称空间可以互通
首先利用ip 命令创建两个网络名称空间
ip netns add ns1
ip netns add ns2
再通过ip link 生成一对虚拟网卡,并将它们加入到两个新建的网络名称空间
生成网卡对
ip link add veth0 type veth peer name veth1
将veth0加入到ns1中
ip link set veth0 netns ns1
将veth1加入到ns2中
ip link set veth1 netns ns2
这是我们查看ns1空间的网卡情况
ip netns exec ns1 ifconfig -a 如下结果:
lo: flags=8<LOOPBACK> mtu 65536
loop txqueuelen 1 (Local Loopback)
RX packets 0 bytes 0 (0.0 B)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 0 bytes 0 (0.0 B)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
veth0: flags=4098<BROADCAST,MULTICAST> mtu 1500
ether 02:8a:bb:52:43:96 txqueuelen 1000 (Ethernet)
RX packets 0 bytes 0 (0.0 B)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 0 bytes 0 (0.0 B)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
我们可以修改veth0为传统的eth0
ip netns exec ns1 ip link set veth0 name eth0
ip netns exec ns2 ip link set veth1 name eth0
我们给两个ns中的网卡配上地址
“`
ip netns exec ns1 ifconfig lo 127.0.0.1/8 up
ip netns exec ns1 ifconfig eth0 192.168.1.111/24 up
ip netns exec ns2 ifconfig lo 127.0.0.1/8 up
ip netns exec ns2 ifconfig eth0 192.168.1.112/24 up
我们让两个ns相互ping
ip netns exec ns1 ping 192.168.1.112
发现可以ping通就说明success