cidr2ip

Small and simple program for converting a CIDR into a netmask
git clone https://noxz.tech/git/cidr2ip.git
Log | Files | README | LICENSE

cidr2ip.c
1/*
2 * Converts CIDR to IPADDRESS
3 * Copyright (C) 2018 z0noxz, <chris@noxz.tech>
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 */
18
19#include <stdlib.h>
20#include <stdio.h>
21#include <string.h>
22#include <unistd.h>
23
24const char *usage = "usage: cidr2ip <CIDR>";
25
26int
27main(int argc, char **argv) {
28	int cidr,
29	    input_size;
30	int buffer_size = 80;
31	char buffer[buffer_size];
32	char *input;
33
34	/* validate input from STDIN */
35	if (!isatty(fileno(stdin)) && fgets(buffer, buffer_size, stdin) != NULL) {
36		input_size = strlen(buffer);
37		input = malloc(input_size);
38		input[0] = '\0';
39		strcat(input, buffer);
40
41	/* validate input from CLI */
42	} else if (argc == 2) {
43		input_size = strlen(argv[1]);
44		input = malloc(input_size);
45		input[0] = '\0';
46		strcat(input, argv[1]);
47
48	/* no valid input, so show usage */
49	} else {
50		fprintf(stderr, "%s\n", usage);
51		return 1;
52	}
53
54	/* check and validate input as cidr */
55	if (sscanf(input, "%d", &cidr) != 1 || cidr < 1 || cidr > 32) {
56		fprintf(stderr, "error: not a CIDR\n");
57		return 1;
58	}
59
60	/* finally print the mask */
61	printf("%d.%d.%d.%d\n",
62		(0xffffffffu << (32-cidr) >> 24) & 0xff,
63		(0xffffffffu << (32-cidr) >> 16) & 0xff,
64		(0xffffffffu << (32-cidr) >>  8) & 0xff,
65		(0xffffffffu << (32-cidr) >>  0) & 0xff
66	);
67
68	return 0;
69}