简体   繁体   中英

Validate an IP and CIDR combo

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
}

Explanation

Let's evaluate 255.255.0.0/16

For ip 255.255.0.0 binary representation of long is 10000000000000000

  1. $ipLong << $prefix Shift 16 bits to left for deleting all network ID bits.
  2. ^ 0 Evaluate if any bit is set after previous operation.
  3. For valid IP and prefix all bits must be unset, so if result is true we have invalid pair.

Tool 'sipcalc' will help you to validate netmask and cidr.

http://www.routemeister.net/

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM