Advertisement
GoodiesHQ

VLSM Calc (C++)

Mar 24th, 2014
176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.84 KB | None | 0 0
  1. #include <iostream>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5.  
  6. using namespace std;
  7.  
  8. int main(int argc, char **argv){
  9.     if(argc!=2){
  10.         fprintf(stderr, "\n\tNo Arguments or Too Many Arguments.\n\t"
  11.             "Usage: %s [CIDR Integer Value]\n\n", *(argv));
  12.         return 1;
  13.     }
  14.     char *mask, *binary;
  15.     unsigned short cidr, octets=4, binval, i;   //cidr value, number of octets, generic counter
  16.  
  17.     if(strlen(*(argv+1))<=2){
  18.         /*  I know it's C++ and I didn't use new()  */
  19.         /*      Allocated all in HEAP       */
  20.         mask = (char*)calloc(16, sizeof(char));     // mask in decimal form
  21.         binary = (char*)calloc(9, sizeof(char));    // binary (in string) which will be converted to long later
  22.         if(!mask || !binary){
  23.             /*  I code in C so I prefer stderr  */
  24.             fprintf(stderr, "\n\tCould Not Allocate Heap Space\n");
  25.             return -1;
  26.         }
  27.     }else{
  28.         fprintf(stderr, "\n\tOut Of Range (0-32)\n");   // Again, using stderr. I'm not sure what C++ convention is for errors
  29.         return 1;
  30.     }
  31.     cidr = strtol(*(argv+1), NULL, 10);         // integer value from command line...
  32.     for(octets=0; octets<4; octets++){
  33.         if(cidr>=8){
  34.             cidr -= 8;
  35.             strcat(mask, "255");
  36.         }else{
  37.             if(cidr==0)
  38.                 strcat(mask, "0");
  39.             else{
  40.                 for(i=0;i<cidr;i++){
  41.                     strcat(binary, "1");
  42.                 }
  43.                 for(i=0;i<(8-cidr);i++){
  44.                     strcat(binary, "0");
  45.                 }
  46.                 binval = strtol(binary, NULL, 2);   // Convert to string
  47.                 cidr=0;                 // set CIDR to 0 now. It's a subnet mask. No more after the last '1' bit
  48.                 free(binary);               // FREE AS A BIRD. AND THIS BIRD YOU CANNOT CHAAAAAANGE
  49.                 binary = (char*)calloc(9,sizeof(char)); // I like to zero out things. Especially strings.
  50.                 snprintf(binary, 9, "%d", binval);  // Write at MOST 9 bytes.
  51.                 strcat(mask, binary);
  52.             }
  53.         }
  54.         if(octets!=3)
  55.             strcat(mask, ".");
  56.     }
  57.     strcat(mask, "\n");
  58.     cout << mask;
  59.     free(binary);
  60.     free(mask);
  61.     return 0;
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement