In the domain of network configuration, determining whether an IP address falls within a specific CIDR subnet is a common task. This article presents a straightforward method for accomplishing this using rudimentary built-in functions.
The algorithm relies on converting both the IP address and the CIDR subnet range into long integers using the ip2long() function. Subsequently, the subnet mask corresponding to the /xx notation in the CIDR range is calculated.
The final step involves performing a bitwise 'and' operation between the IP and subnet mask. If the result matches the subnet, the provided IP address can be confirmed as residing within the specified subnet.
The code below provides an implementation of the aforementioned algorithm:
<code class="php">function cidr_match($ip, $range) { list ($subnet, $bits) = explode('/', $range); if ($bits === null) { $bits = 32; } $ip = ip2long($ip); $subnet = ip2long($subnet); $mask = -1 << (32 - $bits); $subnet &= $mask; // Adjust subnet alignment if necessary return ($ip & $mask) == $subnet; }</code>
This function can be used as follows:
<code class="php">$ips = array('10.2.1.100', '10.2.1.101', '10.5.1.100', '1.2.3.4'); foreach ($ips as $IP) { if (cidr_match($IP, '10.2.0.0/16') == true) { print "You're in the 10.2 subnet\n"; } }</code>
This code will output:
You're in the 10.2 subnet You're in the 10.2 subnet
The above is the detailed content of How to Verify if an IP Address Belongs to a CIDR Subnet?. For more information, please follow other related articles on the PHP Chinese website!