如何检查以太网头是否为 IEEE 802.1Q 类型?

How to check if ethernet header is type IEEE 802.1Q?

我使用pcap_open_offline来解析数据包。我要检查以太网头是否为 IEEE 802.1Q 类型。我知道我需要检查 802.1Q 标签中的前 16 位是否等于 8100,但我不知道该怎么做。或者如果你知道另一种方法我可以试试。

假设您想要一个 C 语言的解决方案,这里有一个简单的实现:

struct ether_header {
    /* destination MAC */
    uint8_t dst_mac[6];
    /* source MAC */
    uint8_t src_mac[6];
    /* EtherType */
    uint16_t ether_type;
};

#define ETHERTYPE_VLAN 0x8100

/* this method gets the packet data read from pcap file and returns 1 if ether type is 802.1Q, 0 otherwise */
int is_IEEE_802_1Q(const uint8_t* packet_data) {
    /* cast ethernet header */
    ether_header* eth_header = (ether_header*)packet_data;

    /* assuming big endian as most pcap files are in big endian */
    if (eth_header->ether_type == ETHERTYPE_VLAN) {
        return 1;
    }

    return 0;
}