【问题标题】:Programming with pcap example使用 pcap 示例编程
【发布时间】:2013-12-14 14:49:09
【问题描述】:

我正在从 http://www.tcpdump.org/pcap.html 学习 libpcap,但我遇到了这段代码的问题:

struct sniff_ethernet {
    u_char ether_dhost[ETHER_ADDR_LEN]; /* Destination host address */
    u_char ether_shost[ETHER_ADDR_LEN]; /* Source host address */
    u_short ether_type; /* IP? ARP? RARP? etc */
};

...

const struct sniff_ethernet *ethernet; /* The ethernet header */
ethernet = (struct sniff_ethernet*)(packet);

我得到了带有交换字节的 ether_type 值。我认为原因是我使用的是 x86_64 little-endian 机器,其中 LSB 位于最低地址,并且在数据包字节流中 ether_type MSB 在 LSB 之前。问题是:示例代码是仅在大端机器上工作还是我遗漏了什么?

【问题讨论】:

    标签: c endianness pcap libpcap


    【解决方案1】:

    http://www.tcpdump.org/pcap.html 的示例代码没有查看以太网类型,因此无论运行它的机器的字节顺序如何,它都能正常工作。它依靠捕获过滤器(“端口 23”)不捕获非 IPv4 流量。

    例如,当您在代码中使用 ether_type 字段的值时,您必须使用 ntohs()

    【讨论】:

    • 我不知道 ntohs(),它解决了我的问题,检测 802.1Q 标记帧,谢谢!
    猜你喜欢
    • 1970-01-01
    • 2018-06-19
    • 2023-01-07
    • 2019-10-07
    • 1970-01-01
    • 2012-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多