cidr2ip

Small and simple program for converting a CIDR into a netmask
git clone https://noxz.tech/git/cidr2ip.git
cidr2ip

commit: b60e33d26125491921523677cde42903edf98fde
parent: aee37d421b3ca3e8726b529def169cbd6db8ff1f
author: Chris Noxz <chris@noxz.tech>
date:   Sun, 14 May 2023 17:07:04 +0200
simplify
Mcidr2ip.c73++++++++++----------
1 file changed, 37 insertions(+), 36 deletions(-)
diff --git a/cidr2ip.c b/cidr2ip.c
@@ -15,6 +15,7 @@
  * You should have received a copy of the GNU General Public License
  * along with this program. If not, see <http://www.gnu.org/licenses/>.
  */
+
 #include <stdlib.h>
 #include <stdio.h>
 #include <string.h>
@@ -24,45 +25,45 @@ const char *usage = "usage: cidr2ip <CIDR>";
 
 int
 main(int argc, char **argv) {
-    int ip, cidr,
-        input_size;
-    int buffer_size = 80;
-    unsigned char mask[4];
-    char buffer[buffer_size];
-    char *input;
+	int cidr,
+	    input_size;
+	int buffer_size = 80;
+	char buffer[buffer_size];
+	char *input;
+
+	/* validate input from STDIN */
+	if (!isatty(fileno(stdin)) && fgets(buffer, buffer_size, stdin) != NULL) {
+		input_size = strlen(buffer);
+		input = malloc(input_size);
+		input[0] = '\0';
+		strcat(input, buffer);
 
-    /* validate input from STDIN */
-    if (!isatty(fileno(stdin)) && fgets(buffer, buffer_size, stdin) != NULL) {
-        input_size = strlen(buffer);
-        input = malloc(input_size);
-        input[0] = '\0';
-        strcat(input, buffer);
+	/* validate input from CLI */
+	} else if (argc == 2) {
+		input_size = strlen(argv[1]);
+		input = malloc(input_size);
+		input[0] = '\0';
+		strcat(input, argv[1]);
 
-    /* validate input from CLI */
-    } else if (argc == 2) {
-        input_size = strlen(argv[1]);
-        input = malloc(input_size);
-        input[0] = '\0';
-        strcat(input, argv[1]);
+	/* no valid input, so show usage */
+	} else {
+		fprintf(stderr, "%s\n", usage);
+		return 1;
+	}
 
-    /* no valid input, so show usage */
-    } else {
-        fprintf(stderr, "%s\n", usage);
-        return 1;
-    }
+	/* check and validate input as cidr */
+	if (sscanf(input, "%d", &cidr) != 1 || cidr < 1 || cidr > 32) {
+		fprintf(stderr, "error: not a CIDR\n");
+		return 1;
+	}
 
-    if (sscanf(input, "%d", &cidr) == 1 && cidr >= 1 && cidr <= 32) {
-        ip = 0xffffffffu >> (32-cidr) << (32-cidr);
-        mask[0] = (ip >>  0) & 0xff;
-        mask[1] = (ip >>  8) & 0xff;
-        mask[2] = (ip >> 16) & 0xff;
-        mask[3] = (ip >> 24) & 0xff;
-    } else {
-        fprintf(stderr, "error: not a CIDR\n");
-        return 1;
-    }
+	/* finally print the mask */
+	printf("%d.%d.%d.%d\n",
+		(0xffffffffu << (32-cidr) >> 24) & 0xff,
+		(0xffffffffu << (32-cidr) >> 16) & 0xff,
+		(0xffffffffu << (32-cidr) >>  8) & 0xff,
+		(0xffffffffu << (32-cidr) >>  0) & 0xff
+	);
 
-    /* finally print the mask */
-    printf("%d.%d.%d.%d\n", mask[3], mask[2], mask[1], mask[0]);
-    return 0;
+	return 0;
 }