网络虚拟化之network namespace

新增一个namspace:

在这里插入代码片
sudo ip netns add netns1
查看是否创建成功
ip netns list
sudo ls /var/run/netns/netns1 
查看namespace中的网络设备
sudo ip netns exec netns1 ip link list
删除namespace
sudo ip netns delete netns1

增加一个自定义的namspace并测试回环网卡网络:

在这里插入代码片
  sudo ip netns add netns1
  ip netns list
  ip netns exec ip link list
  ip netns exec netns1 ip link list
  sudo ip netns exec netns1 ip link list
  sudo ip netns exec netns1 ping 127.0.0.1
  sudo ip netns exec netns1 ip link set dev lo up
  sudo ip netns exec netns1 ping 127.0.0.1
  sudo ip netns exec netns1 ip link list

创建veth设备对,并把设备对的一端放置到自定义的namspace中,执行和测试步骤如下:

在这里插入代码片
  sudo ip link add veth0 type veth peer name veth1/*创建设备对veth0/veth1*/
  ip link /*查看创建的设备对*/
  sudo ip link set veth1 netns netns1/*将设备对的veth1放到自己定义的namespace中*/
  ip link /*查看创建的设备对*/
  sudo ip netns exec netns1 ip link/*查看netns1的设备信息,可以看到veth1已经放置到了对应的namespace中*/
  sudo ip netns exec netns1 ifconfig veth1 10.1.1.1/24 up/*为netns1设备添加ip并设置状态为up*/
  sudo ip netns exec netns1 ip link/*查看是否配置成功*/
  sudo ifconfig veth0 10.1.1.2/24 up /*为设备添加ip并设置状态为up*/
  ifconfig 
  ping 10.1.1.1
  sudo ip netns exec netns1 ifconfig

通过C代码实现namespace隔离

在这里插入代码片
#define _GNU_SOURCE
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/mount.h>
#include <stdio.h>
#include <sched.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>

#define STACK_SIZE (1024*1024)

int checkpoint[2];
static char child_stack[STACK_SIZE];
char* const child_args[]= {
    "/bin/bash",
    NULL
};

int child_main(void* arg) {
    char c;
    close(checkpoint[1]);
    printf("--[%5d] World !\n", getpid());
    sethostname("hw", sizeof("haoweizhang#"));
    
    mount("proc", "/proc", "proc", 0, NULL);

    read(checkpoint[0], &c, 1);
    
    system("ip link set lo up");
    system("ip link set veth1 up");
    system("ip addr add 192.168.1.1/24 dev veth1");
    execv(child_args[0], child_args);
    printf("Doops\n");
    return 1;
}

int main() {
    pipe(checkpoint);
    printf("--[%5d]Hello?\n", getpid());

    int child_pid = clone(child_main, child_stack+STACK_SIZE, CLONE_NEWUTS | CLONE_NEWPID | CLONE_NEWNS | CLONE_NEWIPC | CLONE_NEWNET | SIGCHLD, NULL);
    
    char *cmd;
    asprintf(&cmd, "ip link set veth1 netns %d", child_pid);

    system("ip link add veth0 type veth peer name veth1");

    system(cmd);

    system("ip link set veth0 up");

    system("ip addr add 192.168.1.2/24 dev veth0");

    free(cmd);

    close(checkpoint[1]);

    waitpid(child_pid, NULL, 0);

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值