Skip to content

Instantly share code, notes, and snippets.

@jakekara
Last active February 4, 2018 17:48
Show Gist options
  • Select an option

  • Save jakekara/ea6c505fdf992ea409015cf4a0914d70 to your computer and use it in GitHub Desktop.

Select an option

Save jakekara/ea6c505fdf992ea409015cf4a0914d70 to your computer and use it in GitHub Desktop.
Determine IPv4 class. Just a quick teaching tool for those of us who need to convince ourselves that the most significant bits thing works.
/********************************************************
* ipclass.c
*
* Demonstrate that the first significant bits
* can be used to determine the address class
*
*
* https://en.wikipedia.org/wiki/Classful_network
*******************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv){
/*
* define the starting point for our classes, made easier
* to read with binary constants.
* https://gcc.gnu.org/onlinedocs/gcc/Binary-constants.html
*/
int A = 0b00000000; /* 0 */
int B = 0b10000000; /* 128 2^7 */
int C = 0b11000000; /* 190 2^7 + 2^6*/
int D = 0b11100000; /* 224 2^7 + 2^6 + 2^5 */
int E = 0b11110000; /* 240 2^7 + 2^6 + 2^5 + 2^4*/
/* if no argument supplied, just print the starting point of each class
* and call it a day
*/
if (argc < 2){
printf ("A\t%d.0.0.0\n", A);
printf ("B\t%d.0.0.0\n", B);
printf ("C\t%d.0.0.0\n", C);
printf ("D\t%d.0.0.0\n", D);
printf ("E\t%d.0.0.0\n", E);
return 0;
}
/* chop off input from first 'dot' */
int i = 0;
for ( i = 0; i < strlen(argv[1]); i++){
if (argv[1][i] == '.') { argv[1][i] = '\0'; break; }
}
/* convert chopped input to integer */
int first_bits = atoi(argv[1]);
/* determine the address class */
char class;
if ( first_bits < B){ class = 'A'; }
else if (first_bits < C) { class = 'B'; }
else if (first_bits < D) { class = 'C'; }
else if (first_bits < E) { class = 'D'; }
else { class = 'E'; }
/* print the output */
printf ("%c\n", class);
/* fin. */
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment