cybersecurity · advanced · ~15 min

Parse an IPv4 header from bytes

Parse byte-level network structures defensively.

Challenge

Given the struct

typedef struct {
    unsigned char  version;     // 4 for IPv4
    unsigned char  ihl;         // header length in 32-bit words
    unsigned short total_len;
    unsigned char  protocol;
    unsigned int   src_ip;      // network byte order
    unsigned int   dst_ip;      // network byte order
} ipv4_hdr_t;

implement int parse_ipv4(const unsigned char *buf, size_t n, ipv4_hdr_t *out) that parses a standard 20-byte IPv4 header. Return 0 on success, -1 if n < 20 or the version field is not 4. Pure parser — no live capture, no sockets.

Starter code

#include <stddef.h>
#include <string.h>

int parse_ipv4(const unsigned char *buf, size_t n, ipv4_hdr_t *out) {
    /* TODO */
    return -1;
}

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