I'm coding a network program and i need it to "understand" ip ranges, but i don't know how to make to parse an IP CIDR range, let's say "172.16.10.0/24" to work with the specified IP range.
I've found a program which does it, but i don't understand the code. Here is the function:
static int parse_iprange(char *p)
{
char *e;
u32 ip=0;
int sh;
for(sh = 24;; sh -= 8) {
unsigned long v;
v = strtoul(p, &e, 10);
if(p == e || v > 255)
return 0;
ip |= v << sh;
p = e + 1;
if(*e == '/') {
v = strtoul(p, &e, 10);
if(p == e || *e || v > 32)
return 0;
if(v) {
v = 32 - v;
if(sh > v)
return 0;
mask:
v = ~0 << v;
}
scan.start = ip & v;
scan.end = scan.start - v;
return 1;
}
if(!sh) break;
v = sh;
if(!*e)
goto mask;
if(*e != '.')
return 0;
if(!*p || *p == '*' && !p[1])
goto mask;
}
scan.start = ip;
scan.end = ip + 1;
if(*e == '-') {
u32 end = 0, m = ~0;
do {
unsigned long v = strtoul(p, &e, 10);
if(p == e || v > 255)
return 0;
p = e + 1;
end = end<<8 | v;
m <<= 8;
} while(m && *e);
if(*e)
return 0;
end |= ip & m;
if(end < ip)
return 0;
scan.end = end + 1;
return 1;
}
return *e == 0;
}
So, please, can somebody explain me how to do this or at least, what does this function do?
Hello,
Thanks for your time, i've been testing your code and it has a bug, it works perfectly with any address starting with "128.x.x.x" and lower, but, when you try and address greater than 128, you'll always get the same result, for example, if you input "192.168.1.1/24", the program will show you up "128.168.1.0".
Might it be the power functions incremented by three?