1

我正在尝试使用 #include 解析一个 pcap 文件,其中包括不同类型的网络数据包(有些标记为 VLAN,有些没有)。到目前为止,这是我的代码:

pcap_t *pcap;
const unsigned char *packet;
char errbuf[PCAP_ERRBUF_SIZE];
struct pcap_pkthdr header;
pcap = pcap_open_offline(argv[0], errbuf);
if (pcap == NULL)
    {
    fprintf(stderr, "error reading pcap file: %s\n", errbuf);
    exit(1);
}
while ((packet = pcap_next(pcap, &header)) != NULL)
{
    struct ip_header *ip;
    unsigned int IP_header_length;
    packet += sizeof(struct ether_header);
    capture_len -= sizeof(struct ether_header);
    ip = (struct ip_header*) packet;
    IP_header_length = ip->vhl * 4; /* ip_hl is in 4-byte words */
    char *sinfo = strdup(inet_ntoa(ip->src));
    char *dinfo = strdup(inet_ntoa(ip->dst));
    printf ("%s<-__->%s\n", sinfo ,dinfo);
    free (sinfo);
    free (dinfo);
}

代码中必须有某处检查 VLAN 并正确跳过它们。我应该如何区分 VLAN 数据包和非 VLAN?

4

1 回答 1

1

(如果您在“实时”环境中进行测试,请务必记住路由器可以在转发到非中继线路之前删除 802.1q 标签。)

如果您有特定的平台和协议,最快的方法总是“手动”检查框架:

htonl( ((uint32_t)(ETH_P_8021Q) << 16U)
     | ((uint32_t)customer_tci & 0xFFFFU) ) T

但是,libpcap它以函数的形式提供了一个可移植和干净的数据包过滤器,用于编译 BPF 过滤器并将其应用于数据包流(尽管重要的是要注意,在线与在线有不同的函数集。离线过滤)

以这种方式,我们可以使用pcap_offline_filter将编译后的 BPF 过滤器指令应用于 PCAP 文件。我在vlan这里使用了过滤器表达式,你可能想要别的东西,比如vlan or ip. 如果您需要更复杂的东西,可以查阅文档

...

pcap_t *pcap;
char errbuf[PCAP_ERRBUF_SIZE];
const unsigned char *packet;
struct pcap_pkthdr header;
struct bpf_program fp; // Our filter expression
pcap = pcap_open_offline(argv[0], errbuf);
if (pcap == NULL) {
    fprintf(stderr, "error reading pcap file: %s\n", errbuf);
    exit(1);
}

// Compile a basic filter expression, you can exam
if (pcap_compile(pcap, &fp, "vlan", 0, net) == -1) {
    fprintf(stderr, "Couldn't parse filter %s: %s\n", filter_exp, pcap_geterr(handle));
    return 2;
}

while ((packet = pcap_next(pcap, &header) != NULL)
       && pcap_offline_filter(&fp, header, packet)) {
    struct ip_header *ip;
    unsigned int IP_header_length;
    packet += sizeof(struct ether_header);
    capture_len -= sizeof(struct ether_header);
    ip = (struct ip_header*) packet;
    IP_header_length = ip->vhl * 4; /* ip_hl is in 4-byte words */
    char *sinfo = strdup(inet_ntoa(ip->src));
    char *dinfo = strdup(inet_ntoa(ip->dst));
    printf ("%s<-__->%s\n", sinfo ,dinfo);
    free (sinfo);
    free (dinfo);
}

...
于 2016-09-25T20:43:00.110 回答