"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Verify IP Address Inclusion in a CIDR Subnet?

How to Verify IP Address Inclusion in a CIDR Subnet?

Published on 2024-11-07
Browse:525

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:

function cidr_match($ip, $range)
{
    list ($subnet, $bits) = explode('/', $range);
    if ($bits === null) {
        $bits = 32;
    }
    $ip = ip2long($ip);
    $subnet = ip2long($subnet);
    $mask = -1 
Release Statement This article is reprinted at: 1729251256 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3