cybersecurity · advanced · ~15 min

Parse an IPv4 header from bytes

Parse byte-level network structures defensively.

Challenge

Decode a 20-byte IPv4 header from a raw byte buffer into a struct, bounds-checking first.

The grader supplies this struct (do not redefine it):

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;      // host byte order
    unsigned int   dst_ip;      // host byte order
} ipv4_hdr_t;

Task

Implement int parse_ipv4(const unsigned char *buf, size_t n, ipv4_hdr_t *out) that parses a standard 20-byte IPv4 header from buf into out. No main — the grader calls it. This is a pure parser: no live capture, no sockets.

Input

  • buf: a byte buffer holding a packet header.
  • n: how many bytes are available in buf.
  • out: the struct to fill.

Output

Returns 0 on success (with out populated), or -1 if n < 20 or the version nibble is not 4.

Example

buf = 45 00 00 14 ... 7F 00 00 01 08 08 08 08  (20 bytes)
  ->   version=4, ihl=5, total_len=20, protocol=6, src_ip=0x7F000001, dst_ip=0x08080808
parse_ipv4(buf, 10, &h)   ->   -1   (too short)

Edge cases

  • n < 20 returns -1.
  • A first-byte high nibble other than 4 returns -1.

Rules

  • The first byte holds version (high nibble) and IHL (low nibble). total_len is bytes 2-3 big-endian; src_ip/dst_ip are bytes 12-15 / 16-19; store the IPs in host byte order.

Input format

A byte buffer buf, its length n, and an ipv4_hdr_t out struct.

Output format

0 with out populated on success; -1 if n < 20 or the version is not 4.

Constraints

Bounds-check before reading; store IP addresses in host byte order; do not redefine the struct.

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.