calculate IP range using PHP and CIDR

后端 未结 5 773
故里飘歌
故里飘歌 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

    As you've already noted, all IPv4 addresses can be converted to numbers using ip2long(), and converted back using long2ip(). The critical extra bit I'm not sure you've noticed is that sequential IPs correspond with sequential numbers, so you can manipulate these numbers!

    Given a CIDR prefix (e.g, $prefix = 30 for your range), you can calculate the number of IPs in that range using a bit shift operator:

    $ip_count = 1 << (32 - $prefix);
    

    And then loop through all the IPs in that range using:

    $start = ip2long($start_ip);
    for ($i = 0; $i < $ip_count; $i++) {
        $ip = long2ip($start + $i);
        // do stuff with $ip...
    }
    

提交回复
热议问题