主要参考
[0]Introducing Linux Network Namespaces
veth pair
veth pair是用于不同network namespace间进行通信的方式,veth pair将一个network namespace数据发往另一个network namespace的veth。如下:
Veth pair 是一对虚拟网卡,从一张veth网卡发出的数据包可以直接到达它的peer veth,两者之间存在着虚拟链路。
Veth 网卡和常规的以太网区别仅在于xmit接口:将数据发送到其peer,触发peer的Rx 过程。Veth 的原理示意图如下:
Veth 的实现在linux/drivers/net/veth.c 下,总体来看比较简单:
关键的数据结构:
- struct veth_priv {
- struct net_device __rcu *peer;
- atomic64_t dropped;
- };
- /*
- * tie the deviced together
- */
- priv = netdev_priv(dev);
- rcu_assign_pointer(priv->peer, peer);
- priv = netdev_priv(peer);
- rcu_assign_pointer(priv->peer, dev);
- rcv = rcu_dereference(priv->peer);
- ...
- if (likely(dev_forward_skb(rcv, skb)== NET_RX_SUCCESS)){
- struct pcpu_vstats *stats = this_cpu_ptr(dev->vstats);
- u64_stats_update_begin(&stats->syncp);
- stats->bytes+= length;
- stats->packets++;
- u64_stats_update_end(&stats->syncp);
- } else{
应用方式:通过net namespace 做实验如下:
- #!/bin/sh
- echo "create net namespace net0 and net1"
- ip netns add net0
- ip netns add net1
- echo "list net namespace"
- ip netns list
- echo "add veth pair v1 and vp1"
- ip link add veth_0 type veth peer name veth_0_peer
- ip link
- echo "set veth_0 in net0"
- ip link set veth_0 netns net0
- echo "set veth_0_peer in net1"
- ip link set veth_0_peer netns net1
- ip netns exec net0 ip addr add local 10.0.78.3/24 dev veth_0
- ip netns exec net0 ifconfig veth_0 up
- ip netns exec net1 ip addr add local 10.0.78.4/24 dev veth_0_peer
- ip netns exec net1 ifconfig veth_0_peer up
- echo "show ip netns net0"
- ip netns exec net0 ip addr
- echo "show ip netns net1"
- ip netns exec net1 ip addr
- ip netns exec net1 ping 10.0.78.3