通过 Linux ip_forward 实现两个 netns 通信

发布时间: 更新时间: 总字数:541 阅读时间:2m 作者: IP属地: 分享 复制网址

该示例为 Linux Veth Pair 介绍 的升级,通过 ip_forward 实现两个 ns 通信

示例图

ip_forawrd 配置

修改 /etc/sysctl.conf,添加:

net.ipv4.ip_forward = 1

然后执行如下命令是配置生效:

sysctl -p

cat /proc/sys/net/ipv4/ip_forward1 则已经生效。

创建步骤

# 1. 创建连个 netns
ip netns add ns1
ip netns add ns2

# 2. 创建2对 veth-pair
ip link add veth1-1 type veth peer name veth1-2
ip link add veth2-1 type veth peer name veth2-2

# 3. 2 对 veth-pair 一端分别挂在两个 netns 中,并配置 ip 地址
ip link set veth1-1 netns ns1
ip netns exec ns1 ip addr add 10.0.1.1/24 dev veth1-1
ip netns exec ns1 ip link set veth1-1 up
ip link set veth2-1 netns ns2
ip netns exec ns2 ip addr add 10.0.2.1/24 dev veth2-1
ip netns exec ns2 ip link set veth2-1 up

# 4. 为 2 对 veth-pair 另一端分配 ip 地址
ip addr add 10.0.1.2/24 dev veth1-2
ip link set veth1-2 up
ip addr add 10.0.2.2/24 dev veth2-2
ip link set veth2-2 up

验证

默认是不通的,如:

$ ip netns exec ns1 ping -c 1 10.0.2.1
connect: Network is unreachable

ns1中默认的路由:

$ ip netns exec ns1 ip a
1: lo: <LOOPBACK> mtu 65536 qdisc noop state DOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
7: veth1-1@if6: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default qlen 1000
    link/ether 52:1f:b5:1a:2d:ab brd ff:ff:ff:ff:ff:ff link-netnsid 0
    inet 10.0.1.1/24 scope global veth1-1
       valid_lft forever preferred_lft forever
    inet6 fe80::501f:b5ff:fe1a:2dab/64 scope link
       valid_lft forever preferred_lft forever
$ ip netns exec ns1 route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
10.0.1.0        0.0.0.0         255.255.255.0   U     0      0        0 veth1-1

默认没有到 10.0.2.0/24 的路由,因此ping不通。添加路由:

ip netns exec ns1 route add -net 10.0.2.0 netmask 255.255.255.0 gw 10.0.1.2
ip netns exec ns2 route add -net 10.0.1.0 netmask 255.255.255.0 gw 10.0.2.2

ping 正常:

ip netns exec ns1 ping -c 1 10.0.2.1
PING 10.0.2.1 (10.0.2.1) 56(84) bytes of data.
64 bytes from 10.0.2.1: icmp_seq=1 ttl=63 time=0.107 ms

--- 10.0.2.1 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.107/0.107/0.107/0.000 ms

检查线路链接工具

随着虚拟网卡数量的不断增加,网络环境变得更加复杂,我们可以通过 lldp 协议,清楚看到每个网卡连接到了哪些环境中的哪个网卡。

  • 安装
# ubuntu
apt intall lldpd -y

# redhat
yum install lldpd -y
  • 启动服务
systemctl start lldpd.service
  • 查看
lldpcli show neighbors
Home Archives Categories Tags Statistics
本文总阅读量 次 本站总访问量 次 本站总访客数