C: validating numeric input with strtol

Input from users, files, and the network cannot be trusted. Validate it: check its form, that the whole text was used, and that the value is in range. atoi is unsafe for this because it cannot report errors at all. It returns 0 for text such as abc.

C
#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>

static int parse_port(const char *text, int *out) {
  if (text[0] == '\0' || isspace((unsigned char)text[0])) {
    return 0;
  }
  char *end;
  errno = 0;
  long value = strtol(text, &end, 10);
  if (*end != '\0' || errno == ERANGE || value < 1 || value > 65535) {
    return 0;
  }
  *out = (int)value;
  return 1;
}

int main(void) {
  const char *inputs[] = {"8080", "0", "70000", "80a", "", " 22", "99999999999999999999"};
  for (int i = 0; i < 7; i++) {
    int port;
    if (parse_port(inputs[i], &port)) {
      printf("'%s' -> %d\n", inputs[i], port);
    } else {
      printf("'%s' -> rejected\n", inputs[i]);
    }
  }
  return 0;
}
Read the full lesson