Hello there,
I am looking forward a CIDR parsing code to check if an accessing IP is belonging to a specific CIDR.
Idealy I'd like something like this :
IP_check("192.168.2.0/24")->check("192.168.1.1");
This will return 0 if its doesn't belong to the specified CIDR or 1 it is ok ...
Any clues ?
/Xavier
Totally untested code:
class IPv4_check { static int mask_bits; static int check_bits;
static int ip_to_int( string x ) { int res; foreach( x/".", string x ) { int p = (int)x; res <<= 8; if( p < 0 || p > 255 || (!p && strlen(x-"0")) ) error("Invalid IP. Offending part: "+x+"\n"); res |= (int)x; } return res; }
//! Supported formats: X.X.X.X/BITS //! FIXME: Add more formats static void create( string format ) { int bits; string base; if( sscanf( format, "%s/%d", base, bits ) != 2 ) // Try others error("Failed to parse format\n"); check_bits = ip_to_int( base ); mask_bits = 0xffffffff&~((1<<(32-check_bits))-1); if( check_bits > 32 || check_bits < 1 ) error("Invalid number of bits in the netmask.\n"); check_bits &= mask_bits; }
//! Check whether or not the specified IP matches this pattern //! Also verifies that the IP is a valid IP int check( string ip ) { return (ip_to_int( ip ) & mask_bits) == check_bits; } }
/ Per Hedbor ()
Previous text:
2003-10-01 11:34: Subject: CIDR parsing code ?
Hello there,
I am looking forward a CIDR parsing code to check if an accessing IP is belonging to a specific CIDR.
Idealy I'd like something like this :
IP_check("192.168.2.0/24")->check("192.168.1.1");
This will return 0 if its doesn't belong to the specified CIDR or 1 it is ok ...
Any clues ?
/Xavier
/ Brevbäraren
pike-devel@lists.lysator.liu.se