Safe Penetration Testing Labs · intermediate · ~15 min
Decode the 24-byte global header of a `.pcap` capture file.
Bounds-check, build little-endian integers byte-by-byte, validate the magic, fill the struct.
Every forensic walk through a captured packet trace begins with this 24-byte block. It pins the format.
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.
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)
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).
n < 24. Always check.magic as an int by casting the pointer — alignment-unsafe
on some platforms. Build the integer byte-by-byte with shifts.24 bytes, one struct, one magic-number check. Byte-by-byte reads beat unaligned casts.