Verifying IP Address Inclusion in a CIDR Subnet
To determine whether an IPv4 address falls within a specified CIDR subnet, a straightforward method involves the following steps:
Conversion to Long Integers:
Subnet Mask Derivation:
Bitwise Comparison:
Implementation:
The following PHP function encapsulates this logic:
<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; return ($ip & $mask) == $subnet; }</code>
The above is the detailed content of How to Verify IP Address Inclusion in a CIDR Subnet?. For more information, please follow other related articles on the PHP Chinese website!