一个学习研究的案例

ip netns add ns1                   # 创建命名空间 ns1
ip netns add ns2                   # 创建命名空间 ns2


创建虚拟路由器设备
ip netns add router                # 创建虚拟路由器命名空间
ip link add veth1 type veth peer name veth1-router   # 创建 veth1 和 veth1-router 接口
ip link add veth2 type veth peer name veth2-router   # 创建 veth2 和 veth2-router 接口

ip link set veth1 netns ns1        # 将 veth1 接口移动到命名空间 ns1
ip link set veth2 netns ns2        # 将 veth2 接口移动到命名空间 ns2
ip link set veth1-router netns router   # 将 veth1-router 接口移动到虚拟路由器命名空间
ip link set veth2-router netns router   # 将 veth2-router 接口移动到虚拟路由器命名空间

配置命名空间中的 IP 地址
ip netns exec ns1 ip addr add 192.168.1.2/24 dev veth1   # 配置 veth1 的IP地址为 192.168.1.2/24
ip netns exec ns2 ip addr add 192.168.2.2/24 dev veth2   # 配置 veth2 的IP地址为 192.168.2.2/24
ip netns exec ns1 ip link set veth1 up   # 启用 veth1 接口
ip netns exec ns2 ip link set veth2 up   # 启用 veth2 接口

配置虚拟路由器设备和路由规则
ip netns exec router ip link set lo up   # 在虚拟路由器命名空间中启用 loopback 接口
ip netns exec router ip addr add 192.168.1.1/24 dev veth1-router   # 配置 veth1-router 的IP地址为 192.168.1.1/24
ip netns exec router ip addr add 192.168.2.1/24 dev veth2-router   # 配置 veth2-router 的IP地址为 192.168.2.1/24
ip netns exec router ip link set veth1-router up
ip netns exec router ip link set veth2-router up
ip netns exec router sysctl -w net.ipv4.ip_forward=1   # 启用 IP 转发

ip netns exec ns1 ip route add default via 192.168.1.1   # 在命名空间 ns1 中配置默认路由
ip netns exec ns2 ip route add default via 192.168.2.1   # 在命名空间 ns2 中配置默认路由


Linux中使用虚拟路由器进行不同命名空间之间的通信测试_命名空间

ping 自己需要启动lo接口

ip netns exec ns1 ip link set lo up

ping不通有异常去检查下

ip netns exec router ip route   # 检查虚拟路由器的路由表
ip netns exec router ip addr    # 检查虚拟路由器的网络接口配置

ip netns exec ns1 ip addr      # 检查命名空间ns1的网络接口配置
ip netns exec ns1 ip route     # 检查命名空间ns1的路由表
ip netns exec ns2 ip addr      # 检查命名空间ns2的网络接口配置
ip netns exec ns2 ip route     # 检查命名空间ns2的路由表