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

Implement int classify_ip_string(const char *s) returning:

  • 4 if the string is a candidate IPv4 (contains a . and no :).
  • 6 if it's a candidate IPv6 (contains a :).
  • 0 for anything else (empty, NULL, doesn't look like either).

This is a family-detect gate; you don't have to validate the address — just classify.

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

String.

Output format

4 / 6 / 0.

Constraints

No regex; pure character scan.

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.