Safe Penetration Testing Labs · intermediate · ~15 min

Read the pcap global header in C

Decode the 24-byte global header of a `.pcap` capture file.

Overview

Bounds-check, build little-endian integers byte-by-byte, validate the magic, fill the struct.

Why it matters

Every forensic walk through a captured packet trace begins with this 24-byte block. It pins the format.

Lesson

Why this matters

Wireshark and tcpdump write the same file format: libpcap. Knowing how to walk a .pcap by hand is the difference between using a tool and reading what it produced.

This exercise is the very first step: read the 24-byte file header, confirm the magic number, pull out the snap length and link type.

What the bytes look like

The pcap global header is exactly 24 bytes:

offset  size  field
0       4     magic     (0xa1b2c3d4 host-order, 0xd4c3b2a1 swapped)
4       2     version_major (usually 2)
6       2     version_minor (usually 4)
8       4     thiszone  (signed)
12      4     sigfigs
16      4     snaplen   (max packet size captured)
20      4     linktype  (1 = Ethernet)

Your job

Implement int read_pcap_header(const uint8_t *buf, size_t n, pcap_hdr_t *out). Read the bytes in host order (we're going to assume the dump came from a machine with the same endianness — endian swapping is a follow-up exercise).

Return 0 if the magic matches 0xa1b2c3d4, -1 otherwise (or if n < 24).

Common mistakes

  • Reading past the buffer when n < 24. Always check.
  • Forgetting that the input is a byte array, not a string. There's no NUL.
  • Treating magic as an int by casting the pointer — alignment-unsafe on some platforms. Build the integer byte-by-byte with shifts.

What this is NOT

  • A full pcap walker. Per-record headers and packet payloads are out of scope for this exercise.
  • A live capture tool. We read pre-captured files only.

Summary

24 bytes, one struct, one magic-number check. Byte-by-byte reads beat unaligned casts.

Practice with these exercises