How can I parse an ethernet packet using libpcap?

左心房为你撑大大i 提交于 2019-12-12 12:04:57

问题


I'm using libpcap in C++ for reading packets from pcap files, e.g.:

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

I would like to parse the packets header (without the payload).

For example, how can I parse a given packet in order to extract its source and destintation ip addresses?

thanks


回答1:


Checkout the code sample for libpcap http://www.tcpdump.org/pcap.html

In the 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. For parsing the ethernet headers you just need to use the corresponding pointer

ethernet = (struct sniff_ethernet*)(packet);

For IP layer

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.




回答2:


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. see an example here



来源:https://stackoverflow.com/questions/6111479/how-can-i-parse-an-ethernet-packet-using-libpcap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!