networking · intermediate · ~25 min
Defensive parsing with explicit reject criteria.
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.
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.
ASCII string.
*out = octet0<<24 | octet1<<16 | octet2<<8 | octet3.
No inet_aton, no inet_pton. Reject leading zeros, reject extra characters.
#include <stdint.h>
int ipv4_parse(const char *s, uint32_t *out) { /* TODO */ return 0; }
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.
0.0.0.0. 255.255.255.255. 1.2.3.4.5 (too many) — reject.
O(strlen(s)).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.