1. Vethpair 簡單實驗——實現(xiàn)兩個命名空間互聯(lián)
創(chuàng)建veth-pair
ip netns add charles-netns
ip link add veth0 type veth peer name veth1
ip link set veth1 netns charles-netns
ip addr add 192.168.1.2/24 dev veth0
ip link set dev veth0 up
ip netns exec charles-netns ip addr add 192.168.1.1/24 dev veth1
ip netns exec charles-netns ip link set dev veth1 up
查找veth-pair
ip netns exec charles-netns ethtool -S veth1
2. 網(wǎng)橋?qū)嶒灐獙崿F(xiàn)多個命令空間互聯(lián)
創(chuàng)建兩個命令空間: charles-netns-1, charles-netns-2
ip netns add charles-netns-1
ip netns add charles-netns-2
創(chuàng)建2個veth-pair
ip link add veth1-local type veth peer name veth1-peer
ip link add veth2-local type veth peer name veth2-peer
添加veth1-peer呼胚,veth2-peer到不同的命名空間
ip link set veth1-peer netns charles-netns-1
ip link set veth2-peer netns charles-netns-2
配置veth-pair IP地址
ip addr add 192.168.1.2/24 dev veth1-local
ip addr add 192.168.1.4/24 dev veth2-local
ip netns exec charles-netns-1 ip addr add 192.168.2.2/24 dev veth1-peer
ip netns exec charles-netns-2 ip addr add 192.168.2.4/24 dev veth2-peer
UP網(wǎng)卡
ip link set dev veth1-local up
ip link set dev veth2-local up
ip netns exec charles-netns-1 ip link set dev veth1-peer up
ip netns exec charles-netns-2 ip link set dev veth2-peer up
創(chuàng)建bridge
brctl addbr br0
brctl addif br0 veth1-local
brctl addif br0 veth2-local
ip addr add 192.168.1.1/24 dev br0
ip addr add 192.168.2.1/24 dev br0
ip link set dev br0 up
添加路由
ip netns exec charles-netns-1 ip route add default via 192.168.1.1 dev veth1-peer
ip netns exec charles-netns-2 ip route add default via 192.168.2.1 dev veth2-peer
3. 命名空間網(wǎng)卡訪問外網(wǎng)實驗
MASQUERADE
#打開IP轉(zhuǎn)發(fā)
sysctl -w net.ipv4.conf.all.forwarding=1
#對Namespace中的包添加網(wǎng)絡地址轉(zhuǎn)換
#添加規(guī)則
iptables -t nat -A POSTROUTING -s 192.168.1.0/24 -o eth0 -j MASQUERADE
#刪除規(guī)則
iptables -t nat -D POSTROUTING -s 172.18.0.0/24 -o eth0 -j MASQUERADE
#列出規(guī)則
iptables-save
驗證測試:
ip netns exec charles-netns-1 bash
ping www.baidu.com
PING www.a.shifen.com (220.181.112.244) 56(84) bytes of data.
64 bytes from 220.181.112.244 (220.181.112.244): icmp_seq=1 ttl=52 time=5.37 ms
64 bytes from 220.181.112.244 (220.181.112.244): icmp_seq=2 ttl=52 time=5.43 ms
64 bytes from 220.181.112.244 (220.181.112.244): icmp_seq=3 ttl=52 time=5.42 ms
抓包:
tcpdump -i eth0 -s0 -w eth0.pcap
DNAT
iptables -t nat -A PREROUTING -p tcp -m tcp --dport 80 -j DNAT --to-destination 192.168.1.3:80