Matching IP Addresses to CIDR Subnets
Determining whether an IP address falls within a specific CIDR subnet is a common task in network administration. It allows for efficient mapping and management of IP ranges.
To address this need, let's explore the implementation of a function, cidr_match(), that performs this matching using only built-in or common functions.
Implementation Overview
The algorithm involves converting the IP address and subnet range into long integers using the ip2long() function. Next, the subnet mask is obtained by converting the trailing digits of the subnet range (e.g., "/16") into a bitwise mask. This mask effectively splits the IP address into a network prefix and a host suffix.
Finally, we perform a bitwise AND operation between the IP address and the subnet mask. If the result matches the subnet range, then the IP address is within the specified CIDR subnet.
Function Definition
Here is the implementation of the cidr_match() function:
<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; // Ensure subnet is aligned return ($ip & $mask) == $subnet; }</code>
Example Usage
In the example provided, let's assume we have an array of IP addresses to check:
<code class="php">$ips = ['10.2.1.100', '10.2.1.101', '10.5.1.100', '1.2.3.4'];</code>
We want to verify which of these IPs belong to the subnet "10.2.0.0/16":
<code class="php">foreach ($ips as $IP) { if (cidr_match($IP, '10.2.0.0/16') == true) { print "{$IP} is in the 10.2 subnet\n"; } }</code>
Output:
10.2.1.100 is in the 10.2 subnet 10.2.1.101 is in the 10.2 subnet
This demonstrates the usage of the cidr_match() function to determine whether an IP address falls within a specified CIDR subnet.
The above is the detailed content of How to Determine If an IP Address is Within a CIDR Subnet Using Built-in Functions?. For more information, please follow other related articles on the PHP Chinese website!