【问题标题】:Issue sniffing PCAP问题嗅探 PCAP
【发布时间】:2022-01-03 14:18:19
【问题描述】:

我不明白为什么我的以下代码不能正常工作。 当我嗅探以太网时,我收到的字节移动了 2 个字节

我用sudo sendip -p ipv4 -p udp 127.0.0.1 -d r8发送数据包到我的电脑

使用以下代码:

#include <pcap/pcap.h>

#define SIZE_ETHERNET 14
#define ETHER_ADDR_LEN  6
struct sniff_ethernet {
        u_char  ether_dhost[ETHER_ADDR_LEN];
        u_char  ether_shost[ETHER_ADDR_LEN];
        u_short ether_type;
};


void packet_call_back(u_char *user, const struct pcap_pkthdr *h, const u_char *bytes) { 
    struct sniff_ethernet *ethernet = (struct sniff_ethernet*)(bytes);
    printf("test = %#x\n", ethernet->ether_type); // print is 0x0
}

int     main(void) {
    char    errbuf[PCAP_ERRBUF_SIZE];

    pcap_t  *handle = pcap_create("any", errbuf);
    pcap_set_timeout(handle, -1);
    pcap_loop(handle, 0, packet_call_back, NULL);
    pcap_close(handle);
}

我在这里收到的 ether_type 不正确 0x0000 而不是 0x0800

但如果不是:struct sniff_ethernet *ethernet = (struct sniff_ethernet*)(bytes); 我把struct sniff_ethernet *ethernet = (struct sniff_ethernet*)(bytes + 2); 在这里一切正常,我可以轻松分析我的数据包。

我用gcc test.c -l pcap 编译 我在一个 Ubuntu 虚拟机上工作

感谢阅读

【问题讨论】:

    标签: c ethernet pcap


    【解决方案1】:

    当我嗅探以太网时,我收到的字节移动了 2 个字节

    您不是在嗅探以太网,而是在嗅探“任何”设备。这将在所有接口上捕获,无论它们是否是以太网接口;即使它们都是以太网接口,也没有什么区别。

    为了完成这项工作,在“任何”设备上使用其他 类型的链路层标头而不是以太网。在 Linux 上,这是一个特殊的标头; here's what that header looks like.

    所有程序使用 libpcap 捕获网络流量在打开捕获设备后必须读取捕获文件 (pcap_activate() , pcap_open_live(), pcap_open()) 或捕获文件 (pcap_open_offline()),调用 pcap_datalink() 来确定设备或文件的链路层标头类型。

    该函数返回一个可以在the link-layer header types list 中找到的值;它将是名称以DLT_ 开头的值之一。 检查那里给出的数值;检查DLT_ 值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-24
      • 2013-01-01
      • 2013-07-22
      • 2015-12-13
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多