Kristopher
Kristopher

Reputation: 1748

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?

Upvotes: 3

Views: 4728

Answers (3)

Chaitenya
Chaitenya

Reputation: 329

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

http://www.routemeister.net/

Upvotes: 0

terales
terales

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
}

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.

Upvotes: 2

Gryphius
Gryphius

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

Related Questions