我一直在尝试接收和处理来自隧道的数据包。有单独的块用于处理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);
}
答案 0 :(得分:0)
隧道设备会在IP数据包前附加其他信息,因此第一个字节不是IP版本。如果不需要,可以将IFF_NO_PI
添加到ifr_flags
。参见kernel documentation。