【问题标题】:Problem in reading packets from tunnel using read()使用 read() 从隧道读取数据包的问题
【发布时间】:2021-01-22 04:45:39
【问题描述】:

我一直在尝试接收和处理来自隧道的数据包。有单独的块用于处理 v4 和 v6 数据包。如果数据包不属于任一类别,它们将被丢弃。对我来说,每个数据包在执行过程中都会被丢弃。当我使用wireshark从隧道捕获数据包时,我注意到数据包大小的差异,即数据包的长度。例如,当 Wireshark 中接收到的数据包的长度为 60 时,程序将其打印为 64 作为长度。我注意到所有数据包中有 4 个字节的差异。我无法找出,我在这里做错了什么?有没有人能帮帮我。我还附上了wireshark和程序执行的屏幕以供阅读。

Image: Captured packets from tunnel through wireshark and program

#define MTU 1600
void processPacket(const uint8_t *packet, const size_t len) {
    //1st octet identifies the IP version
    uint8_t version = (*packet) >> 4;
    //...

    printf("IP version - %d\n", version);
    if (version == 4 ) {
        //ipv4 packet process ...
    } else if (version == 6) {
        //ipv6 packet process ...
    } else {
        //drop packet
        printf("Unknown IP version, drop packet\n");
    }
}

int main() {
    struct ifreq ifr;
    int fd;
    uint8_t *buffer = (uint8_t *)(malloc(MTU));
    ssize_t len;

    if ( (fd = open("/dev/net/tun", O_RDWR)) == -1 ) {
        perror("Unable to open /dev/net/tun");
        exit(EXIT_FAILURE);
    }
    memset(&ifr, 0, sizeof(ifr));
    ifr.ifr_flags = IFF_TUN;
    strncpy(ifr.ifr_name, "tun0", IFNAMSIZ);

    if ( (err = ioctl(fd, TUNSETIFF, (void *) &ifr)) == -1 ) {
        perror("Error encountered during ioctl TUNSETIFF");
        close(fd);
        exit(EXIT_FAILURE);
    }

    printf("Device tun0 opened\n");
    while(1) {
        len = read(fd, buffer, MTU);
        printf("Read %lu bytes from tun0\n", len);
        processPacket(buffer, len);
    }

    printf("\nPress any key to exit...");
    getchar();
    close(fd);
}

【问题讨论】:

    标签: sockets ip packet-capture tunnel


    【解决方案1】:

    隧道设备在 IP 数据包前添加附加信息,因此第一个字节不是 IP 版本。如果不需要,可以将IFF_NO_PI添加到ifr_flags。见kernel documentation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-21
      • 1970-01-01
      • 1970-01-01
      • 2021-09-24
      • 2017-02-21
      • 1970-01-01
      相关资源
      最近更新 更多