networking · intermediate · ~25 min

Parse an IPv4 dotted-quad to uint32

Defensive parsing with explicit reject criteria.

Challenge

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.

Task

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).

Input

  • s: an ASCII string in strict dotted-quad form — exactly four decimal octets separated by three dots.

Output

Return 1 on success with *out = (octet0 << 24) | (octet1 << 16) | (octet2 << 8) | octet3. Return 0 on any malformed input.

Example

"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)

Edge cases

  • Each octet is 0..255; a leading zero (e.g. 01) is rejected, but a single 0 is fine.
  • Trailing characters after the fourth octet are rejected.

Rules

  • Do not use inet_aton or inet_pton — parse it yourself.

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

s: an ASCII string in strict dotted-quad form (four octets, three dots).

Output format

1 on success with *out = octet0<<24 | octet1<<16 | octet2<<8 | octet3 (host byte order); 0 on malformed input.

Constraints

No inet_aton/inet_pton; each octet 0..255; reject leading zeros and any trailing 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.