在PHP中从速记中枚举IPv4地址

时间:2011-07-28 01:10:46

标签: php regex

我正在编写一个PHP函数的帮助。我需要接受这样的输入:

192.168.1.1-255
or
192.168.1.1/28

并将其转换为地址数组,例如:

192.168.1.1
192.168.1.2
192.168.1.3
192.168.1.4
192.168.1.5
...

这就是我所处的地方(LOL,不远处):

$remoteAddresses = array('192.168.1.1-255);

foreach($remoteAddresses as &$address) {
  if(preg_match('/(.*)(-\n*)/', $address, $matches)) {
    $address = $matches[1];
  }
}

如果有人有空闲时间想帮助我,我真的不知道我将如何处理192.168.1.1/28语法......

2 个答案:

答案 0 :(得分:1)

您可以尝试以下操作。您可以将结果添加到要构建的阵列中,而不是打印。

$remoteAddresses = array('192.168.1.1-5', '192.168.1.18/25');

foreach($remoteAddresses as $address) {
  if(preg_match('/([0-9\.]+)\.([0-9]+)(\/|\-)([0-9]+)$/', $address, $matches)) {
    $range = range($matches[2], $matches[4]);
    foreach ($range as $line) {
      echo $matches[1] . '.' . $line . '<br />';
    }
  }
}

答案 1 :(得分:1)

我会使用ip2long()和long2ip()来执行IP地址计算。 证明/语法意味着CIDR,它将类似于:

    $remoteAddresses = array('192.168.1.1-5', 
                             '73.35.143.32/27', 
                             '73.35.143.32/30', 
                             '73.35.143.32/32',  
                             '192.168.1.18/25');


    foreach($remoteAddresses as $address) {
      echo "\nRange of IP addresses for $address:\n";
      if(preg_match('/([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)(\-|\/)([0-9]+)$/', $address, $matches)) {
        $ip = $matches[1] . '.' . $matches[2] . '.' . $matches[3] . '.' . $matches[4];
        $ipLong = ip2long($ip);
        if ( $ipLong !== false ) {

            switch( $matches[5] ) {
                case '-':
                    $numIp = $matches[6];
                    break;
                case '/':
                    $cidr = $matches[6];
                    if ( $cidr >= 1 && $cidr <= 32 ) {
                        $numIp = pow(2, 32 - $cidr); // Number of IP addresses in range
                        $netmask = (~ ($numIp - 1)); // Network mask
                        $ipLong = $ipLong & $netmask; // First IP address (even if given IP was not the first in the CIDR range)
                    }
                    else {
                        echo "\t" . "Specified CIDR " . $cidr . " is invalid (should be between 1 and 32)\n";
                        $numIp = -1;
                    }
                    break;
            }

            for ( $ipRange = 0 ; $ipRange < $numIp ; $ipRange++) {
                echo "\t" . long2ip($ipLong + $ipRange) . "\n";
            }      
        }
        else {
            echo "\t" . $ip . " is invalid\n";
        }   
      }
      else  {
          echo "\tUnrecognized pattern: " . $address . "\n";
      }

    }