networking · intermediate · ~25 min
Defensive parsing with explicit reject criteria.
Convert an IPv4 address string like 192.168.1.1 into its 32-bit numeric form — the core of inet_aton and every ACL rule.
Implement int ipv4_parse(const char *s, uint32_t *out). Parse a strict dotted-quad and, on success, set *out to the packed 32-bit value in host byte order (high octet first).
s: an ASCII string in strict dotted-quad form — exactly four decimal octets separated by three dots.Return 1 on success with *out = (octet0 << 24) | (octet1 << 16) | (octet2 << 8) | octet3. Return 0 on any malformed input.
"192.168.1.1" -> 1, *out = 0xC0A80101
"0.0.0.0" -> 1, *out = 0x00000000
"255.255.255.255" -> 1, *out = 0xFFFFFFFF
"192.168.1" -> 0 (only 3 octets)
"192.168.01.1" -> 0 (leading zero)
"256.0.0.0" -> 0 (octet > 255)
"1.2.3.4.5" -> 0 (too many octets)
01) is rejected, but a single 0 is fine.inet_aton or inet_pton — parse it yourself.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.
s: an ASCII string in strict dotted-quad form (four octets, three dots).
1 on success with *out = octet0<<24 | octet1<<16 | octet2<<8 | octet3 (host byte order); 0 on malformed input.
No inet_aton/inet_pton; each octet 0..255; reject leading zeros and any trailing 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.