[英]Enumerating IPv4 Addresses from Shorthand in PHP
I need some help with a PHP function I am writing. 我需要一些关于我正在编写的PHP函数的帮助。 I need to take input like this: 我需要像这样输入:
192.168.1.1-255
or
192.168.1.1/28
and turn it into an array of addresses, such as: 并将其转换为地址数组,例如:
192.168.1.1
192.168.1.2
192.168.1.3
192.168.1.4
192.168.1.5
...
Here's where I am at (LOL, not far at all): 这就是我所处的位置(LOL,不远处):
$remoteAddresses = array('192.168.1.1-255);
foreach($remoteAddresses as &$address) {
if(preg_match('/(.*)(-\n*)/', $address, $matches)) {
$address = $matches[1];
}
}
If anyone has some spare time and wants to help me, I really don't know how I am going to handle the 192.168.1.1/28 syntax... 如果有人有空闲时间想帮助我,我真的不知道我将如何处理192.168.1.1/28语法......
You can try the following. 您可以尝试以下方法。 Instead of printing, you can add the result to the array you want to build. 您可以将结果添加到要构建的阵列中,而不是打印。
$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 />';
}
}
}
I would use the ip2long() and long2ip() to perform the IP address calculations. 我会使用ip2long()和long2ip()来执行IP地址计算。 Proving the / syntax means CIDR, it would be something like: 证明/语法意味着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";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.