Reputation: 1748
I have a user submitted IP address with netmask, and I need to make sure it is valid. For instance, if the user submits: 10.113.0.0/14, I need to flag it as invalid, because the /14 block for that IP range begins with 10.112.0.0.
How can I do this in PHP?
Upvotes: 3
Views: 4728
Reputation: 3200
I had the same question, so posting my result for googlers:
$ipLong = ip2long($ip);
if ( ( ($ipLong << $prefix) ^ 0) == true ) {
//IP and prefix pair is not valid
}
Let's evaluate 255.255.0.0/16
For ip 255.255.0.0 binary representation of long is 10000000000000000
$ipLong << $prefix
Shift 16 bits to left for deleting all network ID bits.^ 0
Evaluate if any bit is set after previous operation.true
we have invalid pair.Upvotes: 2
Reputation: 78906
the function cidrMatch at the bottom of http://framework.zend.com/svn/framework/extras/incubator/library/ZendX/Whois/Adapter/Cidr.php should do what you want
Upvotes: 0