Home > Backend Development > PHP Tutorial > How to Verify if an IP Address Belongs to a CIDR Subnet?

How to Verify if an IP Address Belongs to a CIDR Subnet?

Linda Hamilton
Release: 2024-10-18 19:32:03
Original
597 people have browsed it

How to Verify if an IP Address Belongs to a CIDR Subnet?

Verifying IP Inclusion within a CIDR Subnet

In the domain of network configuration, determining whether an IP address falls within a specific CIDR subnet is a common task. This article presents a straightforward method for accomplishing this using rudimentary built-in functions.

Method

The algorithm relies on converting both the IP address and the CIDR subnet range into long integers using the ip2long() function. Subsequently, the subnet mask corresponding to the /xx notation in the CIDR range is calculated.

The final step involves performing a bitwise 'and' operation between the IP and subnet mask. If the result matches the subnet, the provided IP address can be confirmed as residing within the specified subnet.

Implementation

The code below provides an implementation of the aforementioned algorithm:

<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; // Adjust subnet alignment if necessary
    return ($ip & $mask) == $subnet;
}</code>
Copy after login

This function can be used as follows:

<code class="php">$ips = array('10.2.1.100', '10.2.1.101', '10.5.1.100', '1.2.3.4');

foreach ($ips as $IP) {
    if (cidr_match($IP, '10.2.0.0/16') == true) {
        print "You're in the 10.2 subnet\n";
    }
}</code>
Copy after login

This code will output:

You're in the 10.2 subnet
You're in the 10.2 subnet
Copy after login

The above is the detailed content of How to Verify if an IP Address Belongs to a CIDR Subnet?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template