Skip to content

Instantly share code, notes, and snippets.

@incebellipipo
Created August 27, 2018 13:12
Show Gist options
  • Save incebellipipo/b3f16b031ed17dd305f52cd9b829ab54 to your computer and use it in GitHub Desktop.
Save incebellipipo/b3f16b031ed17dd305f52cd9b829ab54 to your computer and use it in GitHub Desktop.
simple ip calculator
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <arpa/inet.h>
#include <getopt.h>
#include <sys/types.h>
static unsigned char short_opts[] = "i:n:";
static struct option long_options[] = {
{"ip", required_argument, 0, 'i'},
{"netmask", required_argument, 0, 'n'},
};
int main(int argc, char** argv){
struct in_addr ip;
struct in_addr netmask;
int long_index = 0;
while(true){
auto c = getopt_long(argc, argv, (char*)short_opts, long_options, &long_index);
if( c == -1 ){ break; }
switch(c){
case 'i':
inet_aton(optarg, &ip);
break;
case 'n':
inet_aton(optarg, &netmask);
break;
default:
break;
}
}
int subnet_ones = 0;
u_int32_t n = (u_int32_t)netmask.s_addr;
while(n){
subnet_ones += n & 0x1u;
n >>= 1;
}
struct in_addr network;
network.s_addr = ip.s_addr & netmask.s_addr;
struct in_addr broadcast;
broadcast.s_addr = ip.s_addr | ~(netmask.s_addr);
printf("network:\t %s/%d\n", inet_ntoa(network), subnet_ones);
printf("broadcast:\t %s\n", inet_ntoa(broadcast));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment