/*
*ip range test
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
unsigned long ip2ulong(char *ip)
{
unsigned u1, u2, u3, u4;
return sscanf(ip, "%u.%u.%u.%u", &u1, &u2, &u3, &u4) == 4 &&
u1 <= 255 && u2 <= 255 && u3 <= 255 && u4 <= 255
? u1*256*256*256 + u2*256*256 + u3*256 + u4 : 0;
}
int main(int argc, char *argv[])
{
char *ip_str="192.168.20.1/16";
char ip[20];
char str_mask[3];
char *p=NULL;
unsigned long int mask;
bzero(ip, sizeof(ip));
bzero(str_mask, sizeof(str_mask));
if((p=strchr(ip_str,'/'))!=NULL) {
strncpy(ip, ip_str, p-ip_str);
strncpy(str_mask, p+1, sizeof(str_mask));
}
printf("%d mask\n", atoi(str_mask));
mask = ~((1 << (32 - atoi(str_mask))) - 1);
unsigned long startIP=ip2ulong(ip);
printf("%lu ip\n", startIP);
startIP = startIP & mask;
unsigned long endIP = (startIP & mask) | ~mask;
printf("%lu %lu\n", startIP, endIP);
return 0;
*ip range test
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
unsigned long ip2ulong(char *ip)
{
unsigned u1, u2, u3, u4;
return sscanf(ip, "%u.%u.%u.%u", &u1, &u2, &u3, &u4) == 4 &&
u1 <= 255 && u2 <= 255 && u3 <= 255 && u4 <= 255
? u1*256*256*256 + u2*256*256 + u3*256 + u4 : 0;
}
int main(int argc, char *argv[])
{
char *ip_str="192.168.20.1/16";
char ip[20];
char str_mask[3];
char *p=NULL;
unsigned long int mask;
bzero(ip, sizeof(ip));
bzero(str_mask, sizeof(str_mask));
if((p=strchr(ip_str,'/'))!=NULL) {
strncpy(ip, ip_str, p-ip_str);
strncpy(str_mask, p+1, sizeof(str_mask));
}
printf("%d mask\n", atoi(str_mask));
mask = ~((1 << (32 - atoi(str_mask))) - 1);
unsigned long startIP=ip2ulong(ip);
printf("%lu ip\n", startIP);
startIP = startIP & mask;
unsigned long endIP = (startIP & mask) | ~mask;
printf("%lu %lu\n", startIP, endIP);
return 0;
}
The steps would go like this for a network/maskBits
,
You compute the mask
in one of these two ways,
mask = ~((1 << (32 - maskBits)) - 1) // or,
mask = ~(0xFFFFFFFF >> maskBits)
then the range is,
StartIP = network
EndIP = network | ~mask
More precisely,
StartIP = network & mask
EndIP = (network & mask) | ~mask
Where,
-
<<
is bitwise left shift (without rollover) -
&
is bitwise AND, -
|
is bitwise OR, and -
~
is bitwise INVERT.