我不明白为什么下面的代码不能正常工作。当我嗅探以太网时,接收到的字节将被移动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进行工作。
谢谢你的阅读
发布于 2022-01-03 21:07:19
当我嗅探以太网时,接收到的字节将被移动2个字节。
你不是在嗅探以太网,而是在嗅探“任何”设备。这将捕获所有接口,无论它们是否是以太网接口;即使它们都是以太网接口,这也没有什么区别。
为了使此工作,在“任意”设备上使用了以太网以外的链路层报头类型。在Linux上,这是一个特殊的头;以下是标题的样子。
所有使用libpcap捕获网络流量或读取捕获文件的程序必须在打开捕获设备(pcap_activate()、pcap_open_live()、pcap_open())或捕获文件(pcap_open_offline())后调用pcap_datalink()来确定设备或文件中的链路层头类型。
该函数返回一个可以在链接层标题类型列表。中找到的值;它将是以DLT_开头的名称的值之一。不要检查给定的数值;检查DLT_值。
https://stackoverflow.com/questions/70567112
复制相似问题