Skip to content

Instantly share code, notes, and snippets.

@mcastorina
Last active July 10, 2023 20:13
Show Gist options
  • Save mcastorina/156348000a9cf3251dc74cf29d48f71f to your computer and use it in GitHub Desktop.
Save mcastorina/156348000a9cf3251dc74cf29d48f71f to your computer and use it in GitHub Desktop.
IPv4 standard address to integer
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
enum {
ERR_MISSING_OCTETS = 1,
ERR_EXTRA_OCTETS,
ERR_INVALID_OCTET
};
/* convert standard ipv4 to 32-bit uint */
int ip4toi(char *ipstr, uint32_t *res) {
char *tok;
char *endptr;
long digit;
// Clear the existing number.
*res = 0;
// Tokenize the input string by '.'
for (uint8_t i = 0; i < 4; i++) {
tok = strsep(&ipstr, ".");
// We're expecting exactly 4 tokens.
if (tok == NULL) {
return ERR_MISSING_OCTETS;
}
// Make room for the next byte.
*res <<= 8;
// Convert the token to a number.
digit = strtol(tok, &endptr, 10);
// Check to make sure it was a valid octet.
if (*endptr != 0 || digit < 0 || digit > 0xff) {
return ERR_INVALID_OCTET;
}
// Add the digit to the result.
*res |= digit;
}
// Check to make sure we had exactly 4 delimiters.
if (strsep(&ipstr, ".") != NULL) {
return ERR_EXTRA_OCTETS;
}
return 0;
}
const char *errstr(int no) {
switch (no) {
case ERR_MISSING_OCTETS:
return "not enough octets; expected 4";
case ERR_EXTRA_OCTETS:
return "too many octets provided; expected 4";
case ERR_INVALID_OCTET:
return "invalid octet; expected a number between 0-255";
default:
return "no error";
}
}
int main() {
char buf[32];
size_t input_len;
uint32_t result;
int err;
while (true) {
buf[0] = 0;
printf(">> ");
fgets(buf, 32, stdin);
if (buf[0] == 0) {
break;
}
input_len = strnlen(buf, 32);
if (input_len > 0 && buf[input_len-1] == '\n') {
buf[input_len-1] = 0;
}
if ((err = ip4toi(buf, &result)) != 0) {
printf("error: %s\n", errstr(err));
continue;
}
printf("%-10u (0x%08x)\n", result, result);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment