Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I parse an ethernet packet using libpcap?

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

like image 692
user515766 Avatar asked May 24 '11 13:05

user515766


1 Answers

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.

like image 84
Ioannis Pappas Avatar answered Sep 20 '22 05:09

Ioannis Pappas