networking · intermediate · ~25 min

Parse the fixed fields of a mock IPv4 header

Bit extraction from packed fields, plus big-endian 2-byte read.

Challenge

Given a mock IPv4 header in a byte buffer, extract version, internet-header-length (IHL), and total length. We only test parsing — no socket is opened.

Header layout (RFC 791, first 4 bytes of the 20-byte header):

byte 0: [ version: 4 bits ][ IHL: 4 bits ]
byte 1: [ DSCP / ECN, ignore for this exercise ]
bytes 2..3: total length, big-endian

Implement:

int parse_ipv4_header(const unsigned char *buf, size_t len,
                      int *out_version,
                      int *out_ihl,
                      unsigned *out_total_len);

Return 1 on success, 0 if len < 4 or any output pointer is NULL.

Examples

buf = {0x45, 0x00, 0x05, 0xDC, ...}
parse_ipv4_header(buf, 4, &v, &ihl, &tl)
  -> 1, v == 4, ihl == 5, tl == 1500

Why this matters (safety note)

Real packet parsers must validate every field before using it — a corrupted IHL smaller than 5 means the header isn't even fully there. This exercise practices the extraction; you'd add the validation next.

Why this matters

Every packet capture tool, every firewall, every Wireshark plug-in parses IPv4 headers. The structure is fiddly: a 4-bit version, a 4-bit IHL, a big-endian total length — exactly the kind of byte-extraction work where junior engineers regularly produce subtle bugs.

Input format

Byte buffer + length, three output pointers.

Output format

1/0 + populated outputs.

Constraints

Zero allocations; no htons / ntohs — implement the byte assembly yourself.

Starter code

#include <stddef.h>
int parse_ipv4_header(const unsigned char *buf, size_t len,
                      int *out_version,
                      int *out_ihl,
                      unsigned *out_total_len) { /* TODO */ return 0; }

Common mistakes

Reading total_len as host byte order. Mixing the version and IHL nibbles. Forgetting the length check.

Edge cases to handle

len < 4; NULL output pointers; version != 4.

Complexity

O(1).

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.