Home > Article > Backend Development > How to Determine if an IP Address Belongs to a CIDR Subnet Efficiently?
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.
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 &= $mask; # nb: in case the supplied subnet wasn't correctly aligned return ($ip & $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!