networking · intermediate · ~25 min

Parse an IPv4 dotted-quad to uint32

Defensive parsing with explicit reject criteria.

Challenge

Implement int ipv4_parse(const char *s, uint32_t *out). Accepts strict dotted-quad form like 192.168.1.1. Each octet must be 0..255 decimal, no leading zeros (except a literal 0), three dots, four octets. Returns 1 on success with *out in host byte order (high octet first), or 0 on malformed input.

Why this matters

Every routing decision in every network stack uses 32-bit IP addresses internally. Converting 192.168.1.1 to its uint32 form is the kernel of inet_aton, ACL rules, and packet filtering.

Input format

ASCII string.

Output format

*out = octet0<<24 | octet1<<16 | octet2<<8 | octet3.

Constraints

No inet_aton, no inet_pton. Reject leading zeros, reject extra characters.

Starter code

#include <stdint.h>
int ipv4_parse(const char *s, uint32_t *out) { /* TODO */ return 0; }

Common mistakes

Accepting 192.168.01.1 (leading zero in 01 — many tools accept and interpret as octal); accepting 192.168.1 (only 3 octets); accepting trailing garbage.

Edge cases to handle

0.0.0.0. 255.255.255.255. 1.2.3.4.5 (too many) — reject.

Complexity

O(strlen(s)).

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