Created
March 31, 2017 20:29
-
-
Save Orc/c8d9e9b4dd740ca68cd81bb9cc788fea to your computer and use it in GitHub Desktop.
A little program that converts a cidr ip/size into a base/mask pair for tcp wrappers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <sys/socket.h> | |
#include <netinet/in.h> | |
#include <arpa/inet.h> | |
#include <stdarg.h> | |
#include <string.h> | |
#include <libgen.h> | |
#include <unistd.h> | |
#include <stdlib.h> | |
char *pgm = "cidr"; | |
void | |
die(char *why, ...) | |
{ | |
if (why) { | |
va_list args; | |
va_start(args,why); | |
fprintf(stderr, "%s: ", pgm); | |
vfprintf(stderr, why, args); | |
va_end(args); | |
} | |
else | |
fprintf(stderr, "usage: %s ip/width\n", pgm); | |
exit(1); | |
} | |
int | |
main(argc, argv) | |
char **argv; | |
{ | |
char *p; | |
int size; | |
struct in_addr check; | |
in_addr_t addr; | |
in_addr_t netmask; | |
pgm = basename(argv[0]); | |
if ( argc != 2 ) | |
die(0); | |
if ( (p = strchr(argv[1], '/')) == 0 ) | |
die(0); | |
*p++ = 0; | |
if ( (size = atoi(p)) < 1 || size > 32 ) | |
die("width needs to be between 1 & 32"); | |
if ( inet_aton(argv[1], &check) == 0 ) | |
die("incomprehensible IP address %s", argv[1]); | |
/* sanity checking by inet_aton() call above */ | |
addr = ntohl(inet_addr(argv[1])); | |
netmask = (-1) << (32-size); | |
addr &= netmask; | |
check.s_addr = htonl(addr); | |
printf("%s/", inet_ntoa(check)); | |
check.s_addr = htonl(netmask); | |
printf("%s\n", inet_ntoa(check)); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment