5

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

Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
user515766
  • 349
  • 2
  • 5
  • 7
  • 1
    If you want to use C++ why not using a library which wraps libpcap and provides built-in protocol parsers? I can recommend [PcapPlusPlus](https://github.com/seladb/PcapPlusPlus) which I'm using, please see [this tutorial](http://seladb.github.io/PcapPlusPlus-Doc/tutorial_packet_parsing.html) to learn how to parse packets using this library. – John Jul 27 '17 at 23:03

2 Answers2

6

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.

newfurniturey
  • 37,556
  • 9
  • 94
  • 102
Ioannis Pappas
  • 807
  • 12
  • 22
  • Pcap has filters which use data in packet for purpose of filtering. Thus I've concluded it knows what data is where, does it make this available? (e.g. as a header file) – Paweł Szczur Jul 29 '16 at 12:02
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

cpx
  • 17,009
  • 20
  • 87
  • 142