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?
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. Tool 'sipcalc' will help you to validate netmask and cidr.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.