linux下搭建虛擬網(wǎng)絡(luò)拓撲需要用到以下幾個功能:
1麸塞、netns
linux內(nèi)核可以隔離出多個網(wǎng)絡(luò)名稱空間举畸,每個網(wǎng)絡(luò)名稱空間有自己的網(wǎng)絡(luò)協(xié)議棧,路由表等。操作系統(tǒng)默認有一個網(wǎng)絡(luò)名稱空間蠢终,可提供類似于路由器的功能
2惠奸、veth
veth是linux提供的虛擬的網(wǎng)絡(luò)組件占拍,類似于一根網(wǎng)線及兩端的網(wǎng)卡勃教。
3、bridge
linux提供的類似于二層交換機的組件脐嫂。
一痪伦、本示例會創(chuàng)建兩個網(wǎng)絡(luò)名稱空間侄榴,再通過veth接到同一個bridge下,并測試網(wǎng)絡(luò)連通性网沾。
1癞蚕、創(chuàng)建兩個網(wǎng)絡(luò)名稱空間(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桦山、將兩個網(wǎng)絡(luò)名稱空間分別接到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、分別在兩個網(wǎng)絡(luò)名稱空間的虛擬網(wǎng)卡上配上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醋旦、將所有的虛擬網(wǎng)卡及bridge設(shè)置為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恒水、測試網(wǎng)絡(luò)連通性
[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