calculate IP range using PHP and CIDR

后端 未结 5 765
故里飘歌
故里飘歌 2021-01-03 08:47

I\'ve seen various questions and answers around this site and I\'m still having difficulty wrapping my head around this problem (could be because I\'ve got a cold). Regardle

5条回答
  •  旧巷少年郎
    2021-01-03 08:56

    Here is the actual way to calculate a true IP range based on CIDR:

    The top answer is actually not correct. It gives the wrong IP range list.

    function ipRange($cidr) {
       $range = array();
       $cidr = explode('/', $cidr);
       $range[0] = long2ip((ip2long($cidr[0])) & ((-1 << (32 - (int)$cidr[1]))));
       $range[1] = long2ip((ip2long($range[0])) + pow(2, (32 - (int)$cidr[1])) - 1);
       return $range;
    }
    
     var_dump(ipRange("207.64.1.68/28"));
    
     //////////////////OUTPUT////////////////////////
     // array(2) {
     //   [0]=>
     //   string(12) "207.64.1.64"
     //   [1]=>
     //   string(12) "207.64.1.79"
     // }
     /////////////////////////////////////////////////
    

    IP: 207.64.1.68

    Should give me all IPs within 207.64.1.64 and 207.64.1.79

    The other answers do not subtract, they only go from 207.64.1.68 - 207.64.1.83 (not correct in the IP range block)

    You can check it here: https://www.ipaddressguide.com/cidr

提交回复
热议问题