Skip to content

Instantly share code, notes, and snippets.

@mtortonesi
Created December 2, 2020 17:08
Show Gist options
  • Save mtortonesi/465134b6870ad1cbe7b09cc964ade8cb to your computer and use it in GitHub Desktop.
Save mtortonesi/465134b6870ad1cbe7b09cc964ade8cb to your computer and use it in GitHub Desktop.
#include <errno.h>
#include <stdlib.h>
#include <limits.h>
#include <stdio.h>
int get_port(const char *str)
{
long ret;
char *endptr;
ret = strtol(str, &endptr, 10);
if (ret == 0 && errno == EINVAL) {
// nessuna conversione effettuata
return -1;
}
if (errno == ERANGE) {
if (ret == LONG_MIN) {
// underflow
return -2;
} else { // ret == LONG_MAX
// overflow
return -3;
}
}
if (ret < 0 || ret > 65535) {
// valore letto al di fuori del range di porte consentite
return -4;
}
if (*endptr != '\0') {
// non necessariamente un errore, ma condizione da segnalare
fprintf(stderr, "attenzione: possibile problema!\n");
}
return (int)ret;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment