networking · intermediate · ~15 min
Validate a whole hostname.
Validate a whole hostname string before handing it to getaddrinfo.
Implement int hostname_valid(const char *h).
h: a NUL-terminated candidate hostname.Return 1 if h is non-empty and every character is a valid hostname character (letter, digit, -, or .); else 0.
hostname_valid("example.com") -> 1
hostname_valid("") -> 0 (empty)
hostname_valid("a b.com") -> 0 (space not allowed)
h: a NUL-terminated candidate hostname.
1 if h is non-empty and every character is valid (letter, digit, '-', '.'); else 0.
Reject the empty string; every character must be in a-z, A-Z, 0-9, '-', '.'.
int hostname_valid(const char *h) {
/* TODO */
return 0;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.