networking · intermediate · ~25 min
Bit extraction from packed fields, plus big-endian 2-byte read.
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.
buf = {0x45, 0x00, 0x05, 0xDC, ...}
parse_ipv4_header(buf, 4, &v, &ihl, &tl)
-> 1, v == 4, ihl == 5, tl == 1500
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.
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.
Byte buffer + length, three output pointers.
1/0 + populated outputs.
Zero allocations; no htons / ntohs — implement the byte assembly yourself.
#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; }
Reading total_len as host byte order. Mixing the version and IHL nibbles. Forgetting the length check.
len < 4; NULL output pointers; version != 4.
O(1).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.