跟着网上作一次,OK的。

tun.c

#include <net/if.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <sys/types.h>
#include <linux/if_tun.h>
#include<stdlib.h>
#include<stdio.h>

int tun_alloc(int flags)
{

    struct ifreq ifr;
    int fd, err;
    char *clonedev = "/dev/net/tun";

    ) {
        return fd;
    }

    memset(&ifr, , sizeof(ifr));
    ifr.ifr_flags = flags;

    ) {
        close(fd);
        return err;
    }

    printf("Open tun/tap device: %s for reading...\n", ifr.ifr_name);

    return fd;
}

int main()
{

    int tun_fd, nread;
    ];

    /* Flags: IFF_TUN   - TUN device (no Ethernet headers)
     *        IFF_TAP   - TAP device
     *        IFF_NO_PI - Do not provide packet information
     */
    tun_fd = tun_alloc(IFF_TUN | IFF_NO_PI);

    ) {
        perror("Allocating interface");
        exit();
    }

    ) {
        nread = read(tun_fd, buffer, sizeof(buffer));
        ) {
            perror("Reading from interface");
            close(tun_fd);
            exit();
        }

        printf("Read %d bytes from tun/tap device\n", nread);
    }
    ;
}

编译之后运行:

gcc tun.c -o tun

在一个终端里开启tun程序

./tun

在另一终端里,将生成的tun0设备配置IP及激活,然后进行tcpdump抓包

ip addr add  dev tun0

ip link set tun0 up

tcpdump -i tun0

在第三个终端里,Ping命令,然后查看前两个终端输出,即可知道tun通道有数据通过。

 192.168.128.66

实操《kubernetes网络权威指南》之tun设备-LMLPHP

实操《kubernetes网络权威指南》之tun设备-LMLPHP

05-11 23:02