How can I parse an ethernet packet using libpcap?

I use libpcap in C ++ to read packages from pcap files, for example:

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

I would like to parse the packet header (no payload).

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

thanks

+4
source share
2 answers

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

In got_packet(u_char *args, const struct pcap_pkthdr *header, const u_char *packet); function got_packet(u_char *args, const struct pcap_pkthdr *header, const u_char *packet); there is a *packet pointer pointing to the beginning of the packet. To parse ethernet headers you just need to use the appropriate pointer

 ethernet = (struct sniff_ethernet*)(packet); 

For IP level

 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 analyze the payload, you can (or not) define a pointer to the beginning of the payload.

+5
source

The IP header data fields are packed in big-endian order, and the packet payload is attached immediately after the IP header. see example here

+2
source

All Articles