Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- using namespace std;
- int main(int argc, char **argv){
- if(argc!=2){
- fprintf(stderr, "\n\tNo Arguments or Too Many Arguments.\n\t"
- "Usage: %s [CIDR Integer Value]\n\n", *(argv));
- return 1;
- }
- char *mask, *binary;
- unsigned short cidr, octets=4, binval, i; //cidr value, number of octets, generic counter
- if(strlen(*(argv+1))<=2){
- /* I know it's C++ and I didn't use new() */
- /* Allocated all in HEAP */
- mask = (char*)calloc(16, sizeof(char)); // mask in decimal form
- binary = (char*)calloc(9, sizeof(char)); // binary (in string) which will be converted to long later
- if(!mask || !binary){
- /* I code in C so I prefer stderr */
- fprintf(stderr, "\n\tCould Not Allocate Heap Space\n");
- return -1;
- }
- }else{
- fprintf(stderr, "\n\tOut Of Range (0-32)\n"); // Again, using stderr. I'm not sure what C++ convention is for errors
- return 1;
- }
- cidr = strtol(*(argv+1), NULL, 10); // integer value from command line...
- for(octets=0; octets<4; octets++){
- if(cidr>=8){
- cidr -= 8;
- strcat(mask, "255");
- }else{
- if(cidr==0)
- strcat(mask, "0");
- else{
- for(i=0;i<cidr;i++){
- strcat(binary, "1");
- }
- for(i=0;i<(8-cidr);i++){
- strcat(binary, "0");
- }
- binval = strtol(binary, NULL, 2); // Convert to string
- cidr=0; // set CIDR to 0 now. It's a subnet mask. No more after the last '1' bit
- free(binary); // FREE AS A BIRD. AND THIS BIRD YOU CANNOT CHAAAAAANGE
- binary = (char*)calloc(9,sizeof(char)); // I like to zero out things. Especially strings.
- snprintf(binary, 9, "%d", binval); // Write at MOST 9 bytes.
- strcat(mask, binary);
- }
- }
- if(octets!=3)
- strcat(mask, ".");
- }
- strcat(mask, "\n");
- cout << mask;
- free(binary);
- free(mask);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement