【发布时间】:2016-09-05 09:37:35
【问题描述】:
这段代码在 Ubuntu 16.04 上运行良好,并且当我通过环回接口折腾 UDP 字节时打印正确的值 (ETHERTYPE_IP):
#include <pcap.h>
#include <iostream>
#include <net/ethernet.h>
int main(int argc,char **argv)
{
char errbuf[PCAP_ERRBUF_SIZE];
auto pcap = pcap_open_live("lo0", BUFSIZ, 0, 1000, errbuf);
pcap_loop(pcap,0, [] (u_char *self, const struct pcap_pkthdr *header,
const u_char *packet) {
auto eth = (struct ether_header *) packet;
auto eth_type = ntohs(eth->ether_type);
std::cout << "eth_type: " << std::hex << eth_type << std::endl;
}, nullptr);
return 0;
}
网猫:
➜ ~ nc -uv -l 54321
Listening on [0.0.0.0] (family 0, port 54321)
➜ ~ nc -4u localhost 54321
hello
程序输出:
➜ ~ sudo ./a.out
eth_type: 800
但是在 OS X 10.11.5 上它会打印 eth_type: 4011。有趣的是,它与 en1 适配器配合良好。
为什么环回和非环回适配器之间存在如此大的差异,在两者上捕获数据包的正确方法是什么?
更新: tcpdump 也可以:
➜ ~ sudo tcpdump -i lo0
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on lo0, link-type NULL (BSD loopback), capture size 262144 bytes
15:09:00.160664 IP localhost.54321 > localhost.63543: UDP, length 4
【问题讨论】:
-
您可能必须使用“lo0”而不是“lo”。要在 Mac 上编译,请尝试:clang++ -std=c++11 -stdlib=libc++ -lpcap test.cpp -o test ...我还得到了 ether_type 的垃圾值。
-
这是sn-p的错字,确实是lo0。
标签: c++ macos endianness libpcap