Matching an IP to a CIDR mask in PHP 5?

前端 未结 13 1083
无人共我
无人共我 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:37

    Just a note, Alnitak's answer works 32/64 bit.

    Here is a cooked version of it, for quick spam protection based on country IP lists that you can get everywhere. google for country ip list or country ip block (Have to give one here, really difficult to find it in that sites page navigation:Country ip block generator)

    Copy-paste your cidr ip list to string $cidrs. And put this code just before page html, possibly in the header.php file.

    Can also be used to filter adsense use in page templates based on country.

    This is only a in-the-middle-of-the-night-urgency solution. Sometimes one needs to come up with something like this for a client quickly yesterday, so here it is.

    //++++++++++++++++++++++
    //COUNTRY SPAM PROTECTOR
    //speed: ~5ms @ 2000 cidrs
    //comments start with #
    //++++++++++++++++++++++
    $cidrs=
    '
    #yourcountry
    1.3.4.5/21
    #mycountry
    6.7.8.9/20
    ';
    //$cidrs.="\n".'123.12.12.12/32';//test, your ip
    $cidrs_ar=preg_split('/\s+/',$cidrs,-1,PREG_SPLIT_NO_EMPTY);
    $ip=@$_SERVER['REMOTE_ADDR'];
    $iplong=ip2long($ip);
    //var_export($cidrs_ar);var_export($ip);var_export($iplong);
    if($iplong)
      foreach($cidrs_ar as $cidr)
        {
        $ar=explode ('/', $cidr);
        $netiplong=ip2long($ar[0]);
        if($netiplong===false) continue;
        $mask=intval(@$ar[1]);
        if(!$mask) continue;
        $bitmask=-1 <<(32-$mask);
        if(($iplong & $bitmask) == ($netiplong & $bitmask))
            {
            header('Location: http://www.someotherwebsite.com/',true,303);
            exit;
            }
        }
    

提交回复
热议问题