P2P: 用于2个netns之间通信,接口直连。

配置:

ip netns add n1
ip netns add n2

ip link add veth1 type veth peer name veth2

ip link set dev veth1 netns n1
ip link set dev veth2 netns n2

ip netns exec n1 ip link set lo up
ip netns exec n1 ip link set veth1 up
ip netns exec n1 ip addr add 10.0.0.1/24 dev veth1

ip netns exec n2 ip link set lo up
ip netns exec n2 ip link set veth2 up
ip netns exec n2 ip addr add 10.0.0.2/24 dev veth2

测试:

# ip netns exec n1 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_req=1 ttl=64 time=0.202 ms
64 bytes from 10.0.0.2: icmp_req=2 ttl=64 time=0.177 ms
64 bytes from 10.0.0.2: icmp_req=3 ttl=64 time=0.163 ms
^C
--- 10.0.0.2 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 1998ms
rtt min/avg/max/mdev = 0.163/0.180/0.202/0.022 ms


Bridge mode:用于多个netns之间互相通信,这种情况下,可以借助host的bridge来实现。

配置:

ip netns add n11
ip netns add n12
ip netns add n13

ip link add veth11 type veth peer name veth11_host
ip link add veth12 type veth peer name veth12_host
ip link add veth13 type veth peer name veth13_host

ip link set dev veth11 netns n11
ip link set dev veth12 netns n12
ip link set dev veth13 netns n13

ip netns exec n11 ip link set dev veth11 name eth0
ip netns exec n12 ip link set dev veth12 name eth0
ip netns exec n13 ip link set dev veth13 name eth0

ip netns exec n11 ip addr add 20.0.0.1/24 dev eth0
ip netns exec n12 ip addr add 20.0.0.2/24 dev eth0
ip netns exec n13 ip addr add 20.0.0.3/24 dev eth0

ip netns exec n11 ip link set dev eth0 up
ip netns exec n12 ip link set dev eth0 up
ip netns exec n13 ip link set dev eth0 up

ip link add br1 type bridge
ip link set dev br1 up

ip link set dev veth11_host master br1
ip link set dev veth12_host master br1
ip link set dev veth13_host master br1

ip link set dev veth11_host up
ip link set dev veth12_host up
ip link set dev veth13_host up

iptables -A FORWARD -i br1 -j ACCEPT

 测试:

# ip netns exec n12 ping 20.0.0.1
PING 20.0.0.1 (20.0.0.1) 56(84) bytes of data.
64 bytes from 20.0.0.1: icmp_req=1 ttl=64 time=0.643 ms
64 bytes from 20.0.0.1: icmp_req=2 ttl=64 time=0.427 ms
64 bytes from 20.0.0.1: icmp_req=3 ttl=64 time=0.438 ms
^C
--- 20.0.0.1 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 1998ms
rtt min/avg/max/mdev = 0.427/0.502/0.643/0.102 ms
[router] / # ip netns exec n12 ping 20.0.0.3
PING 20.0.0.3 (20.0.0.3) 56(84) bytes of data.
64 bytes from 20.0.0.3: icmp_req=1 ttl=64 time=0.603 ms
64 bytes from 20.0.0.3: icmp_req=2 ttl=64 time=0.446 ms
^C
--- 20.0.0.3 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 999ms
rtt min/avg/max/mdev = 0.446/0.524/0.603/0.081 ms
[router] / #