From 51daae4c1d706513cc4c3210165d7defcddf31eb Mon Sep 17 00:00:00 2001 From: Nick Chambers Date: Tue, 4 Jan 2022 22:46:19 -0600 Subject: [PATCH] c/decip4.c: Finally, the ability to turn an IPv4 address into an integer --- c/decip4.c | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 c/decip4.c diff --git a/c/decip4.c b/c/decip4.c new file mode 100644 index 0000000..6047ab2 --- /dev/null +++ b/c/decip4.c @@ -0,0 +1,26 @@ +#include +#include + +uint32_t numeric_ip4(const char *ip) { + uint32_t octets = 0; + uint8_t octet = 0; + + for(; *ip; ip += 1) { + if(*ip == '.') { + octets = (octets << 8) | octet; + octet = 0; + } else { + octet = (octet * 10) + (*ip - '0'); + } + } + + return (octets << 8) | octet; +} + +int main(int argc, char **argv) { + for(argv += 1, argc -= 1; *argv; argv += 1, argc -= 1) { + printf("%s: %u\n", *argv, numeric_ip4(*argv)); + } + + return 0; +}