Matching an IP to a CIDR mask in PHP 5?

前端 未结 13 1121
无人共我
无人共我 2020-11-28 04:04

I\'m looking for quick/simple method for matching a given IP4 dotted quad IP to a CIDR notation mask.

I have a bunch of IPs I need to see if they match a range of IP

13条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 04:25

    If only using IPv4:

    • use ip2long() to convert the IPs and the subnet range into long integers
    • convert the /xx into a subnet mask
    • do a bitwise 'and' (i.e. ip & mask)' and check that that 'result = subnet'

    something like this should work:

    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;
    }
    

提交回复
热议问题