Home  >  Article  >  Backend Development  >  How to Determine if an IP Address Belongs to a CIDR Subnet Efficiently?

How to Determine if an IP Address Belongs to a CIDR Subnet Efficiently?

Susan Sarandon
Susan SarandonOriginal
2024-10-18 19:27:29584browse

How to Determine if an IP Address Belongs to a CIDR Subnet Efficiently?

Determining CIDR Subnet Inclusion of IP Addresses

In many network applications, the need arises to verify whether an IP address belongs to a given CIDR subnet. This question explores a quick and efficient method for such comparisons.

To achieve this, a function, cidr_match(), is employed. It accepts two parameters: the IP address in dotted-quad format and the CIDR notation mask.

Implementation

The first step involves converting both the IP address and the subnet into long integers using ip2long(). The CIDR subnet is then parsed to determine the subnet mask based on the number of bits specified.

Next, a bitwise AND operation is performed between the IP address and the subnet mask. If the result matches the subnet, it indicates that the IP address falls within the specified subnet.

Here's the code snippet for the cidr_match() function:

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 &amp;= $mask; # nb: in case the supplied subnet wasn't correctly aligned
    return ($ip &amp; $mask) == $subnet;
}

By using this function, you can efficiently determine whether an IP address belongs to a particular CIDR subnet. The simplicity and efficiency of this approach make it suitable for a wide range of network-related applications.

The above is the detailed content of How to Determine if an IP Address Belongs to a CIDR Subnet Efficiently?. 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