networking · intermediate · ~15 min

Is the hostname well-formed?

Validate a whole hostname.

Challenge

Validate a whole hostname string before handing it to getaddrinfo.

Task

Implement int hostname_valid(const char *h).

Input

  • h: a NUL-terminated candidate hostname.

Output

Return 1 if h is non-empty and every character is a valid hostname character (letter, digit, -, or .); else 0.

Example

hostname_valid("example.com")  ->  1
hostname_valid("")             ->  0   (empty)
hostname_valid("a b.com")      ->  0   (space not allowed)

Edge cases

  • The empty string is invalid.
  • A single disallowed character anywhere makes the whole name invalid.

Input format

h: a NUL-terminated candidate hostname.

Output format

1 if h is non-empty and every character is valid (letter, digit, '-', '.'); else 0.

Constraints

Reject the empty string; every character must be in a-z, A-Z, 0-9, '-', '.'.

Starter code

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.