linux下搭建虚拟网络拓扑需要用到以下几个功能:
1、netns
linux内核可以隔离出多个网络名称空间,每个网络名称空间有自己的网络协议栈,路由表等。操作系统默认有一个网络名称空间,可提供类似于路由器的功能
2、veth
veth是linux提供的虚拟的网络组件,类似于一根网线及两端的网卡。
3、bridge
linux提供的类似于二层交换机的组件。
一、本示例会创建两个网络名称空间,再通过veth接到同一个bridge下,并测试网络连通性。
1、创建两个网络名称空间(router1和router2)、两组veth,一个bridge(br0)
[root@localhost ~]# ip netns add router1
[root@localhost ~]# ip netns add router2
[root@localhost ~]# ip link add veth1.1 type veth peer name veth1.2
[root@localhost ~]# ip link add veth2.1 type veth peer name veth2.2
[root@localhost ~]# ip link add br0 type bridge
2、将两个网络名称空间分别接到br0上
[root@localhost ~]# ip link set veth1.1 master br0
[root@localhost ~]# ip link set veth2.1 master br0
[root@localhost ~]# ip link set veth1.2 netns router1
[root@localhost ~]# ip link set veth1.2 netns router2
3、分别在两个网络名称空间的虚拟网卡上配上ip
[root@localhost ~]# ip -n router1 address add 10.0.0.1/24 dev veth1.2
[root@localhost ~]# ip -n router2 address add 10.0.0.2/24 dev veth2.2
4、将所有的虚拟网卡及bridge设置为up
[root@localhost ~]# ip link set br0 up
[root@localhost ~]# ip link set veth1.1 up
[root@localhost ~]# ip link set veth2.1 up
[root@localhost ~]# ip -n router1 link set veth1.2 up
[root@localhost ~]# ip -n router2 link set veth2.2 up
5、测试网络连通性
[root@localhost ~]# ip netns exec router1 ping 10.0.0.2
PING 10.0.0.2 (10.0.0.2) 56(84) bytes of data.
64 bytes from 10.0.0.2: icmp_seq=1 ttl=64 time=0.321 ms
64 bytes from 10.0.0.2: icmp_seq=2 ttl=64 time=0.048 ms