从PHP获取CIDR表示法中的IP列表

时间:2011-02-08 10:10:16

标签: php ip cidr

是否有方法(或函数/类)从CIDR表示法获取IP地址列表?

例如,我有73.35.143.32/27 CIDR,并希望获得此表示法中所有IP的列表。有什么建议吗?

谢谢。

14 个答案:

答案 0 :(得分:20)

我会修改aforementioned class以包含一个方法。这是我提出的代码,可能会帮助你。

function cidrToRange($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(cidrToRange("73.35.143.32/27"));

//////////////////OUTPUT////////////////////////
// array(2) {
//   [0]=>
//   string(12) "73.35.143.32"
//   [1]=>
//   string(12) "73.35.143.63"
// }
/////////////////////////////////////////////////

返回ip范围的低端作为数组中的第一个条目,然后返回高端作为第二个条目。

答案 1 :(得分:10)

嗯,它是一个位掩码 - 73.35.143.32/27表示27位是网络掩码,其余的可用于分配给网络中的节点:

73.35.143.32
二进制中的

就是这个(显示易读性的点):

01001001.00100011.10001111.00100000

网络掩码是27位:

11111111.11111111.11111111.11100000

所以你可以和他们在一起得到这个:

01001001.00100011.10001111.001 00000
 network prefix (27 bits)     | node address (5 bits)

从这里,你可以枚举节点地址中的所有组合(00000是0,11111是31,所以一个简单的循环就足够了),你将拥有所有可用的主机。

将此伪代码转换为PHP是留给读者的练习;)

哦,强制弃用警告:IPv4现已满,请考虑使用IPv6。

答案 2 :(得分:5)

这是一个快速的64位功能,请评论您不需要的返回线。接受任何有效的Ipv4,有或没有有效的CIDR路由前缀,例如63.161.156.0/ 24 或63.161.156.0

<?php
function cidr2range($ipv4){
if ($ip=strpos($ipv4,'/'))
{$n_ip=(1<<(32-substr($ipv4,1+$ip)))-1;   $ip_dec=ip2long(substr($ipv4,0,$ip)); }
else
{$n_ip=0;                                   $ip_dec=ip2long($ipv4);             }
$ip_min=$ip_dec&~$n_ip;
$ip_max=$ip_min+$n_ip;
#Array(2) of Decimal Values Range
return [$ip_min,$ip_max];
#Array(2) of Ipv4 Human Readable Range
return [long2ip($ip_min),long2ip($ip_max)];
#Array(2) of Ipv4 and Subnet Range
return [long2ip($ip_min),long2ip(~$n_ip)];
#Array(2) of Ipv4 and Wildcard Bits
return [long2ip($ip_min),long2ip($n_ip)];
#Integer Number of Ipv4 in Range
return ++$n_ip;
}

要快速运行,该功能不会检查输入,但正式它应该是与以下正则表达式匹配的字符串

#^(?:((?:0)|(?:2(?:(?:[0-4][0-9])|(?:5[0-5])))|(?:1?[0-9]{1,2}))\.((?:0)|(?:2(?:(?:[0-4][0-9])|(?:5[0-5])))|(?:1?[0-9]{1,2}))\.((?:0)|(?:2(?:(?:[0-4][0-9])|(?:5[0-5])))|(?:1?[0-9]{1,2}))\.((?:0)|(?:2(?:(?:[0-4][0-9])|(?:5[0-5])))|(?:1?[0-9]{1,2}))(?:/((?:(?:0)|(?:3[0-2])|(?:[1-2]?[0-9]))))?)$#

如果您想在使用功能

之前验证输入
<?php
if (is_string($ipv4) && preg_match('#^(?:((?:0)|(?:2(?:(?:[0-4][0-9])|(?:5[0-5])))|(?:1?[0-9]{1,2}))\.((?:0)|(?:2(?:(?:[0-4][0-9])|(?:5[0-5])))|(?:1?[0-9]{1,2}))\.((?:0)|(?:2(?:(?:[0-4][0-9])|(?:5[0-5])))|(?:1?[0-9]{1,2}))\.((?:0)|(?:2(?:(?:[0-4][0-9])|(?:5[0-5])))|(?:1?[0-9]{1,2}))(?:/((?:(?:0)|(?:3[0-2])|(?:[1-2]?[0-9]))))?)$#',$ipv4))
{
#This is a valid ipv4 with or without CIDR Routing Prefix
$result=cidr2range($ipv4);
print_r($result);
}

获取全范围作为给定IP的数组(有或没有CIDR路由前缀),您可以使用以下代码但要小心,因为例如25.25.25.25/16返回一个数组使用65536个元素,您可以使用较小的路由前缀

轻松耗尽内存
<?php
$result=cidr2range($ipv4);
for($ip_dec=$result[0];$ip_dec<=$result[1];$ip_dec++)
$full_range[$ip_dec]=long2ip($ip_dec);
print_r($full_range);

要快速检查给定的 ipv4是否与给定的CIDR匹配,您可以像在此示例中那样内联

<?php
$given_cidr='55.55.55.0/24';
$given_ipv4='55.55.55.55';
if(($range=cidr2range($given_cidr)) &&
($check=ip2long($given_ipv4))!==false &&
$check>=$range[0] && $check<=$range[1])
{
echo 'Yes, '.$given_ipv4.' is included in '.$given_cidr;
}
else
{
echo 'No, '.$given_ipv4.' is not included in '.$given_cidr;
}

快速检查给定的 ipv4是否与给定的IP数组匹配(有或没有CIDR路由前缀)

<?php
#This code is checking if a given ip belongs to googlebot
$given_ipv4='74.125.61.208';
$given_cidr_array=['108.59.93.43/32','108.59.93.40/31','108.59.93.44/30','108.59.93.32/29','108.59.93.48/28','108.59.93.0/27','108.59.93.64/26','108.59.93.192/26','108.59.92.192/27','108.59.92.128/26','108.59.92.96/27','108.59.92.0/27','108.59.94.208/29','108.59.94.192/28','108.59.94.240/28','108.59.94.128/26','108.59.94.16/29','108.59.94.0/28','108.59.94.32/27','108.59.94.64/26','108.59.95.0/24','108.59.88.0/22','108.59.81.0/27','108.59.80.0/24','108.59.82.0/23','108.59.84.0/22','108.170.217.128/28','108.170.217.160/27','108.170.217.192/26','108.170.217.0/25','108.170.216.0/24','108.170.218.0/23','108.170.220.0/22','108.170.208.0/21','108.170.192.0/20','108.170.224.0/19','108.177.0.0/17','104.132.0.0/14','104.154.0.0/15','104.196.0.0/14','107.167.160.0/19','107.178.192.0/18','125.17.82.112/30','125.16.7.72/30','74.125.0.0/16','72.14.192.0/18','77.109.131.208/28','77.67.50.32/27','66.102.0.0/20','66.227.77.144/29','66.249.64.0/19','67.148.177.136/29','64.124.98.104/29','64.71.148.240/29','64.68.64.64/26','64.68.80.0/20','64.41.221.192/28','64.41.146.208/28','64.9.224.0/19','64.233.160.0/19','65.171.1.144/28','65.170.13.0/28','65.167.144.64/28','65.220.13.0/24','65.216.183.0/24','70.32.132.0/23','70.32.128.0/22','70.32.136.0/21','70.32.144.0/20','85.182.250.128/26','85.182.250.0/25','80.239.168.192/26','80.149.20.0/25','61.246.224.136/30','61.246.190.124/30','63.237.119.112/29','63.226.245.56/29','63.158.137.224/29','63.166.17.128/25','63.161.156.0/24','63.88.22.0/23','41.206.188.128/26','12.234.149.240/29','12.216.80.0/24','8.34.217.24/29','8.34.217.0/28','8.34.217.32/27','8.34.217.64/26','8.34.217.128/25','8.34.216.0/24','8.34.218.0/23','8.34.220.0/22','8.34.208.128/29','8.34.208.144/28','8.34.208.160/27','8.34.208.192/26','8.34.208.0/25','8.34.209.0/24','8.34.210.0/23','8.34.212.0/22','8.35.195.128/28','8.35.195.160/27','8.35.195.192/26','8.35.195.0/25','8.35.194.0/24','8.35.192.0/23','8.35.196.0/22','8.35.200.0/21','8.8.8.0/24','8.8.4.0/24','8.6.48.0/21','4.3.2.0/24','23.236.48.0/20','23.251.128.0/19','216.239.32.0/19','216.252.220.0/22','216.136.145.128/27','216.33.229.160/29','216.33.229.144/29','216.34.7.176/28','216.58.192.0/19','216.109.75.80/28','216.74.130.48/28','216.74.153.0/27','217.118.234.96/28','208.46.199.160/29','208.44.48.240/29','208.21.209.0/28','208.184.125.240/28','209.185.108.128/25','209.85.128.0/17','213.200.103.128/26','213.200.99.192/26','213.155.151.128/26','199.192.112.224/29','199.192.112.192/27','199.192.112.128/26','199.192.112.0/25','199.192.113.176/28','199.192.113.128/27','199.192.113.192/26','199.192.113.0/25','199.192.115.80/28','199.192.115.96/27','199.192.115.0/28','199.192.115.128/25','199.192.114.192/26','199.192.114.0/25','199.223.232.0/21','198.108.100.192/28','195.16.45.144/29','192.104.160.0/23','192.158.28.0/22','192.178.0.0/15','206.160.135.240/28','207.223.160.0/20','203.222.167.144/28','173.255.125.72/29','173.255.125.80/28','173.255.125.96/27','173.255.125.0/27','173.255.125.128/25','173.255.124.240/29','173.255.124.232/29','173.255.124.192/27','173.255.124.128/29','173.255.124.144/28','173.255.124.160/27','173.255.124.48/29','173.255.124.32/28','173.255.124.0/27','173.255.124.64/26','173.255.126.0/23','173.255.122.128/26','173.255.122.64/26','173.255.123.0/24','173.255.121.128/26','173.255.121.0/25','173.255.120.0/24','173.255.117.32/27','173.255.117.64/26','173.255.117.128/25','173.255.116.192/27','173.255.116.128/26','173.255.116.0/25','173.255.118.0/23','173.255.112.0/22','173.194.0.0/16','172.102.8.0/21','172.253.0.0/16','172.217.0.0/16','162.216.148.0/22','162.222.176.0/21','180.87.33.64/26','128.177.109.0/26','128.177.119.128/25','128.177.163.0/25','130.211.0.0/16','142.250.0.0/15','146.148.0.0/17'];
echo '<pre>';
$in_range=false;
if (($given_ipv4_dec=ip2long($given_ipv4))!==false)
{
foreach($given_cidr_array as $given_cidr){
if(($range=cidr2range($given_cidr)) &&
$given_ipv4_dec>=$range[0] && $given_ipv4_dec<=$range[1])
{
$in_range=true;
echo $given_ipv4.' matched '.$given_cidr.' ('.join(array_map('long2ip',$range),' - ').")\n";
}
}
}
echo $given_ipv4.' is probably'.($in_range?'':' not').' a Googlebot IP';
  

希望这几行帮助你......

答案 3 :(得分:4)

有一个小修复 - 当有人放置ip前缀如:127.0.0.15/26这个函数返回坏的最后一个IP地址。在这个函数中,第4行(开始:$ range [1] ...)将 $ cidr [0] 更改为 $ range [0] - 现在返回最后IP地址适用于范围内的每个IP。

function cidrToRange($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(cidrToRange("127.0.0.15/26"));

修复前:

array(2) {
  [0]=>
  string(9) "127.0.0.0"
  [1]=>
  string(10) "127.0.0.78"
}
string(41) "127.0.0.15/26 >> 2130706432 -> 2130706510"

修复后:

array(2) {
  [0]=>
  string(9) "127.0.0.0"
  [1]=>
  string(10) "127.0.0.63"
}
string(41) "127.0.0.15/26 >> 2130706432 -> 2130706495"

答案 4 :(得分:1)

我不相信this class会返回IP列表,但它确实提供了一些有用的方法来处理CIDR块。

答案 5 :(得分:1)

扩展到@jonavon的答案。如果您需要IP的平面列表。您可以像下面这样转换他的功能。

function cidrToRange($value) {
    $range = array();
    $split = explode('/', $value);
    if (!empty($split[0]) && is_scalar($split[1]) && filter_var($split[0], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
        $rangeStart = ip2long($split[0]) & ((-1 << (32 - (int)$split[1])));
        $rangeEnd = ip2long($split[0]) + pow(2, (32 - (int)$split[1])) - 1;

        for ($i = $rangeStart; $i <= $rangeEnd; $i++) {
            $range[] = long2ip($i);
        }
        return $range;
    } else {
        return $value;
    }
}

答案 6 :(得分:1)

强烈推荐此PHP库: https://github.com/S1lentium/IPTools

它可以通过许多功能轻松操纵网络。

例如遍历网络IP地址:

$network = Network::parse('192.168.1.0/24');
foreach($network as $ip) {
    echo (string)$ip . '<br>';
}

// output:
192.168.1.0
...
192.168.1.255

答案 7 :(得分:0)

这将返回一个ips数组:

function get_list_ip($ip_addr_cidr){
    $ip_arr = explode("/", $ip_addr_cidr);    
    $bin = "";

    for($i=1;$i<=32;$i++) {
        $bin .= $ip_arr[1] >= $i ? '1' : '0';
    }

    $ip_arr[1] = bindec($bin);

    $ip = ip2long($ip_arr[0]);
    $nm = $ip_arr[1];
    $nw = ($ip & $nm);
    $bc = $nw | ~$nm;
    $bc_long = ip2long(long2ip($bc));

    for($zm=1;($nw + $zm)<=($bc_long - 1);$zm++)
    {
        $ret[]=long2ip($nw + $zm);
    }
    return $ret;
}

答案 8 :(得分:0)

我想出了一个更好的主意

$ip_from= long2ip(ip2long($ip)& (-1<<(32-$net_mask)));
$ip_to= long2ip(ip2long($ip)| (~(-1<<(32-$net_mask))));

P.S:$ ip是一个类似于60.12.34.5的ipv4地址; $ net_mask是一个类似于25的int网络掩码;

由于位移操作,它的速度非常快

答案 9 :(得分:0)

使用匿名函数迭代CIDR块中的每个IP地址:

cidrl('194.168.0.1/28', $error_code, function($address) {
    // Do something.
    print "$address\n";
});

或者,作为一个数组:

$addresses = cidrl('194.168.0.1/28', $error_code);

来源:

function cidrl($cidr, &$error_code = 0, $callback = null) {
    $error_code = 0;
    sscanf($cidr, "%[^/]/%u", $network, $bits); 
    $addr = ip2long($network);
    if ($addr === false) {
        $error_code = 2;
        return false;
    }       

    if ($bits == 32) {
        if (is_callable($callback)) {
            $callback(long2ip($addr));
            return array(); 
        }           
        return array(long2ip($addr));
    }       

    if ($bits > 32) { 
        $error_code = 3;
        return false;
    }       

    $mask = ~(0xFFFFFFFF >> $bits); 

    $addr_start = $addr & $mask;
    $addr_end = ($addr & $mask) | ~$mask; 

    $addresses = array();
    for ($i = $addr_start; $i <= $addr_end; $i++) { 
        if (is_callable($callback)) $callback(long2ip($i));
        else $addresses[] = long2ip($i);
    }       
    return $addresses;
}

代码来自:https://github.com/emden-norfolk/cidrl/tree/master/php

答案 10 :(得分:0)

我之前写了一个完整的类来很好地处理这个任务(对于另一种语言),并且感谢 PHP 的 ip2long(...) 方法,我们不需要在 PHP 中手动计算。

但我的单元测试数据可用于测试任何其他答案:

<?php
// Below has "CIDR = Minimum ... Maximum" format.
$validRangeMap = [
    '0.0.0.0/1=0.0.0.0...127.255.255.255',
    '128.0.0.0/2=128.0.0.0...191.255.255.255',
    '192.0.0.0/9=192.0.0.0...192.127.255.255',
    '192.128.0.0/11=192.128.0.0...192.159.255.255',
    '192.160.0.0/13=192.160.0.0...192.167.255.255',
    '192.168.0.0/19=192.168.0.0...192.168.31.255',
    '192.168.32.0/21=192.168.32.0...192.168.39.255',
    '192.168.40.0/23=192.168.40.0...192.168.41.255',
    '192.168.42.0/23=192.168.42.0...192.168.43.255',
    '192.168.44.0/22=192.168.44.0...192.168.47.255',
    '192.168.48.0/20=192.168.48.0...192.168.63.255',
    '192.168.64.0/18=192.168.64.0...192.168.127.255',
    '192.168.128.0/17=192.168.128.0...192.168.255.255',
    '192.169.0.0/16=192.169.0.0...192.169.255.255',
    '192.170.0.0/15=192.170.0.0...192.171.255.255',
    '192.172.0.0/14=192.172.0.0...192.175.255.255',
    '192.176.0.0/12=192.176.0.0...192.191.255.255',
    '192.192.0.0/10=192.192.0.0...192.255.255.255',
    '193.0.0.0/8=193.0.0.0...193.255.255.255',
    '194.0.0.0/7=194.0.0.0...195.255.255.255',
    '196.0.0.0/6=196.0.0.0...199.255.255.255',
    '200.0.0.0/5=200.0.0.0...207.255.255.255',
    '208.0.0.0/4=208.0.0.0...223.255.255.255',
    '224.0.0.0/4=224.0.0.0...239.255.255.255',
    '240.0.0.0/5=240.0.0.0...247.255.255.255',
    '248.0.0.0/6=248.0.0.0...251.255.255.255',
    '252.0.0.0/7=252.0.0.0...253.255.255.255',
    '254.0.0.0/8=254.0.0.0...254.255.255.255',
    '255.0.0.0/9=255.0.0.0...255.127.255.255',
    '255.128.0.0/10=255.128.0.0...255.191.255.255',
    '255.192.0.0/11=255.192.0.0...255.223.255.255',
    '255.224.0.0/12=255.224.0.0...255.239.255.255',
    '255.240.0.0/13=255.240.0.0...255.247.255.255',
    '255.248.0.0/14=255.248.0.0...255.251.255.255',
    '255.252.0.0/15=255.252.0.0...255.253.255.255',
    '255.254.0.0/16=255.254.0.0...255.254.255.255',
    '255.255.0.0/17=255.255.0.0...255.255.127.255',
    '255.255.128.0/18=255.255.128.0...255.255.191.255',
    '255.255.192.0/19=255.255.192.0...255.255.223.255',
    '255.255.224.0/20=255.255.224.0...255.255.239.255',
    '255.255.240.0/21=255.255.240.0...255.255.247.255',
    '255.255.248.0/22=255.255.248.0...255.255.251.255',
    '255.255.252.0/23=255.255.252.0...255.255.253.255',
    '255.255.254.0/24=255.255.254.0...255.255.254.255',
    '255.255.255.0/25=255.255.255.0...255.255.255.127',
    '255.255.255.128/26=255.255.255.128...255.255.255.191',
    '255.255.255.192/27=255.255.255.192...255.255.255.223',
    '255.255.255.224/28=255.255.255.224...255.255.255.239',
    '255.255.255.240/29=255.255.255.240...255.255.255.247',
    '255.255.255.248/30=255.255.255.248...255.255.255.251',
    '255.255.255.252/31=255.255.255.252...255.255.255.253',
    '255.255.255.254/32=255.255.255.254...255.255.255.254',
];

示例

我们可以测试 Jonavon's answer,例如:

foreach ($validRangeMap as $entry) {
    $expected = preg_split('/(=|(\.\.\.))+/', $entry);
    $actual = cidrToRange($expected[0]);

    if ($actual[0] !== $expected[1]) {
        echo "Test-Failed! '$actual[0]' should be equal '$expected[1]' <br>" . PHP_EOL;
    } else if ($actual[1] !== $expected[2]) {
        echo "Test-Failed! '$actual[1]' should be equal '$expected[2]' <br>" . PHP_EOL;
    } else {
        echo "Tested '$expected[0]' CIDR <br>" . PHP_EOL;
    }
}

function cidrToRange($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;
}
<块引用>

注意它通过了测试。

答案 11 :(得分:-1)

HeJ小鼠。我也需要这个功能,我编辑另外一个来返回范围内所有IP地址的列表。 这将返回CIDR表示法的IP地址列表。享受它;)

<?php 

    $ip_addr_cidr = "192.256.0.0/16";
    $ip_arr = explode('/', $ip_addr_cidr);

    $bin = '';
    for($i=1;$i<=32;$i++) {
        $bin .= $ip_arr[1] >= $i ? '1' : '0';
    }
    $ip_arr[1] = bindec($bin);

    $ip = ip2long($ip_arr[0]);
    $nm = ip2long($ip_arr[1]);
    $nw = ($ip & $nm);
    $bc = $nw | (~$nm);

    echo "Number of Hosts:    " . ($bc - $nw - 1) . "<br/>";
    echo "Host Range:         " . long2ip($nw + 1) . " -> " . long2ip($bc - 1) . "<br/>". "<br/>";

    for($zm=1;($nw + $zm)<=($bc - 1);$zm++)
        {
        echo long2ip($nw + $zm).  "<br/>";
        }

    ?>

答案 12 :(得分:-1)

修复版的Kosmonaft脚本:

function get_list_ip($ip_addr_cidr){

        $ip_arr = explode("/", $ip_addr_cidr);    
        $bin = "";

        for($i=1;$i<=32;$i++) {
            $bin .= $ip_arr[1] >= $i ? '1' : '0';
        }

        $ip_arr[1] = bindec($bin);

        $ip = ip2long($ip_arr[0]);
        $nm = $ip_arr[1];
        $nw = ($ip & $nm);
        $bc = $nw | ~$nm;
        $bc_long = ip2long(long2ip($bc));

        echo "Number of Hosts:    " . ($bc_long - $nw - 1) . "<br/>";
        echo "Host Range:         " . long2ip($nw + 1) . " -> " . long2ip($bc - 1) . "<br/>". "<br/>";

        for($zm=1;($nw + $zm)<=($bc_long - 1);$zm++)
        {
            echo long2ip($nw + $zm).  "<br/>";
        }
    }

答案 13 :(得分:-1)

我在以前的版本中遇到了一些问题,各种PHP错误,例如未定义的偏移等等。

我发现我认为这是一种更好的方法,没有下面详述的错误。

这采用IPV4 CIDR表示法IP地址,可用于获取CIDR范围的起始/结束IP地址或计算IP地址数据库中的IP地址总数。

namespace MyNameSpace.GlobalServices
{
    class MyGlobalService : IGlobalService
    {
        public ILogger Logger { get; set; }

        public MyGlobalService ()
        {               
            Logger.Debug("My Service Starting...") 
            // no DI happening, getting exception because "Logger" is null

}}}(...)

这里的秘诀是我创建$ ip_arr变量的方式。我没有使用PHP爆炸,而是为每个IP地址手动设置数组维度。这当然是代码的数据库版本,并循环遍历数据库中符合搜索条件的所有IP地址。