简体   繁体   English

如何使用 libpcap 解析以太网数据包?

[英]How can I parse an ethernet packet using libpcap?

I'm using libpcap in C++ for reading packets from pcap files, eg:我在 C++ 中使用 libpcap 从 pcap 文件中读取数据包,例如:

rc = pcap_next_ex((pcap_t*)handle, &header, (const unsigned char**)packet);

I would like to parse the packets header (without the payload).我想解析数据包 header (没有有效负载)。

For example, how can I parse a given packet in order to extract its source and destintation ip addresses?例如,如何解析给定数据包以提取其源和目标 ip 地址?

thanks谢谢

Checkout the code sample for libpcap http://www.tcpdump.org/pcap.html查看 libpcap http://www.tcpdump.org/pcap.html的代码示例

In the got_packet(u_char *args, const struct pcap_pkthdr *header, const u_char *packet);got_packet(u_char *args, const struct pcap_pkthdr *header, const u_char *packet); function you have a pointer *packet that points to the start of the packet. function 你有一个指针*packet指向数据包的开头。 For parsing the ethernet headers you just need to use the corresponding pointer要解析以太网标头,您只需要使用相应的指针

ethernet = (struct sniff_ethernet*)(packet);

For IP layer对于 IP 层

ip = (struct sniff_ip*)(packet + SIZE_ETHERNET);

If you want to parse other protocols, you just need to define your own structures.如果你想解析其他协议,你只需要定义你自己的结构。 If you want (or do not want) to parse the payload then you can (or not) define a pointer to the start of the payload.如果您想要(或不想要)解析有效负载,那么您可以(或不)定义指向有效负载开头的指针。

The data fields of IP headers are packed in big-endian order and the packet payload is attached right after at the end of IP header. IP 标头的数据字段以大端顺序打包,数据包有效负载紧跟在 IP header 的末尾。 see an example here在这里看一个例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM