Home >Backend Development >PHP Tutorial >How to Verify IP Address Inclusion in a CIDR Subnet?

How to Verify IP Address Inclusion in a CIDR Subnet?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-18 19:35:03695browse

How to Verify IP Address Inclusion in a CIDR Subnet?

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:

  • Utilize the ip2long() function to convert both the IP address and the subnet range into long integers.

Subnet Mask Derivation:

  • If the subnet mask is not explicitly provided (/xx), assume a default mask of /32.
  • Compute the subnet mask by applying a left shift of 1s to 32 minus the mask length.

Bitwise Comparison:

  • Perform a bitwise AND operation between the IP long integer and the subnet mask.
  • Check if the result is equal to the subnet long integer.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn