php根据ip段生成ip列表

格式:iplist(‘192.168.1.1,192.168.1.1/26,192.168.1.64-192.168.1.100’);
自动去重、过滤无效ip。

<?php
function iplist($list,$split=','){
    $list=explode($split, $list);
    $newlist=array();
    foreach ($list as $ip) {
        //echo $ip."n";
        if(strpos($ip, '/')!==false){//掩码形式
            $range = array();
            $cidr = explode('/', $ip);
            $range[0] = (ip2long($cidr[0])) & ((-1 << (32 - (int)$cidr[1])))+1;
            $range[1] = (ip2long($cidr[0])) + pow(2, (32 - (int)$cidr[1])) - 1;
            for($i=$range[0];$i<$range[1];$i++){
                array_push($newlist,long2ip($i));
            }
  
        }else if(strpos($ip, '-')!==false){//ip段模式
            $range = array();
            $cidr = explode('-', $ip);
            $range[0] = ip2long($cidr[0]);
            $range[1] = ip2long($cidr[1])+1;
            for($i=$range[0];$i<$range[1];$i++){
                array_push($newlist,long2ip($i));
            }            
        }else{//ip地址
            array_push($newlist, $ip);
        }
    }
    $newlist=array_merge(array_unique($newlist));
    foreach ($newlist as $idx=>$ip) {
    if(!filter_var($ip, FILTER_VALIDATE_IP)){
        array_splice($newlist,$idx,1); 
        }
    }
    
    $iplist=array_merge($newlist);
    return $iplist;
}
print_r(iplist('192.168.1.1,192.168.1.1/26,192.168.1.64-192.168.1.100,192.168.1.1000'));
?>

输出:

woldy@woldy-PC MINGW64 /home/woldy/woldyForce
$ php iptest.php
Array
(
    [0] => 192.168.1.1
    [1] => 192.168.1.2
    [2] => 192.168.1.3
    [3] => 192.168.1.4
    [4] => 192.168.1.5
    [5] => 192.168.1.6
    [6] => 192.168.1.7
    ……
    [97] => 192.168.1.98
    [98] => 192.168.1.99
    [99] => 192.168.1.100
)

woldy@woldy-PC MINGW64 /home/woldy/woldyForce
$

发表评论

电子邮件地址不会被公开。 必填项已用*标注