networking · beginner · ~15 min

Parse an IP literal into a discriminated v4/v6 union

The v4-vs-v6 family-detect heuristic that real parsers use before calling inet_pton.

Challenge

Glance at an IP-address string and tell whether it looks like IPv4 or IPv6 — the lightweight gate a real parser uses before picking AF_INET vs AF_INET6 for inet_pton.

Task

Implement int classify_ip_string(const char *s) that classifies (does not validate) the address family.

Input

  • s: a candidate IP-address string (may be NULL).

Output

Return:

  • 6 if the string contains a : (candidate IPv6 — colon wins).
  • 4 if it contains a . but no : (candidate IPv4).
  • 0 for NULL, empty, or anything with neither.

Example

"192.168.1.1"      ->  4
"::1"              ->  6
"fe80::1"          ->  6
"::ffff:1.2.3.4"   ->  6   (IPv4-mapped IPv6 is still v6 — colon wins)
"not-an-ip"        ->  0
""                 ->  0
NULL               ->  0

Edge cases

  • A string with both : and . (e.g. ::ffff:1.2.3.4) classifies as 6.
  • NULL or empty returns 0.

Rules

  • Classify only; do not validate the address. Pure character scan, no regex.

Why this matters

A modern parser must accept both '192.168.1.1' and '::1'. Detecting the family from the string is the lightweight gate before calling inet_pton.

Input format

s: a candidate IP-address string (may be NULL).

Output format

6 if it contains ':'; else 4 if it contains '.'; else 0 (NULL/empty/neither).

Constraints

Classify only, don't validate; colon takes priority; pure character scan, no regex.

Starter code

int classify_ip_string(const char *s) { /* TODO */ (void)s; return 0; }

Common mistakes

Matching : inside an IPv4-mapped IPv6 like ::ffff:1.2.3.4 and getting confused — that string IS v6.

Edge cases to handle

NULL, empty, just dots, just colons.

Complexity

O(strlen).

Background lessons

Up next

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