我正在通过这个 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 之前。问题是:示例代码只能在大端机器上运行还是我遗漏了什么?
最佳答案
示例代码位于 http://www.tcpdump.org/pcap.html不查看以太网类型,因此无论运行它的机器的字节顺序如何,它都能正常工作。它依赖于捕获过滤器(“端口 23”)不捕获非 IPv4 流量。
例如,当您在代码中使用它的值时,您必须在 ether_type
字段上使用 ntohs()
。
关于c - 使用 pcap 示例编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20584686/