networking · beginner · ~15 min
The v4-vs-v6 family-detect heuristic that real parsers use before calling inet_pton.
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.
Implement int classify_ip_string(const char *s) that classifies (does not validate) the address family.
s: a candidate IP-address string (may be NULL).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."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
: and . (e.g. ::ffff:1.2.3.4) classifies as 6.0.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.
s: a candidate IP-address string (may be NULL).
6 if it contains ':'; else 4 if it contains '.'; else 0 (NULL/empty/neither).
Classify only, don't validate; colon takes priority; pure character scan, no regex.
int classify_ip_string(const char *s) { /* TODO */ (void)s; return 0; }
Matching : inside an IPv4-mapped IPv6 like ::ffff:1.2.3.4 and getting confused — that string IS v6.
NULL, empty, just dots, just colons.
O(strlen).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.