-7

如何从 IP/掩码中找到主机数量(例如:190.200.22.32/255.255.255.224)?

我检查了所有功能: http: //php.net/manual/en/ref.network.php

但我无法实现它。

请帮忙。

谢谢, 腰带

4

1 回答 1

2

您不需要 PHP 来执行此操作。掩码为您提供子网中主机可用的位数。面具中的最大值为 32。255.255.255.0 是 24 位(每个竞争的八位字节是 8 位)。所以你有 2^(32-24) -2 个主机。因此,在这种情况下,您有 254 个主机。

您可以在 PHP 中执行的操作类似于

$octets = explode(".",$mask);
$i=0;
 while($octets[$i]==255){
    $i++;
 }
 $interestingOctet=$octets[$i];
 //count the number of bits in the interesting part. 
 $maskbits = ($i+1)*8 + substr_count(decbin($interestingOctet),1);
 echo pow(2,$maskbits)-2; //this is the number of hosts for this subnet mask

为了找到所有 IP 的范围,您应该找到 IP 地址的二进制表示,并使用子网掩码的二进制表示进行按位布尔运算。这将为您提供子网编号。然后反转掩码(将所有 1 更改为 0,将所有 0 更改为 1)并对子网号(您在上一步中找到)执行按位 BOOLEAN OR。结果是广播地址。您可用的所有 IP 都是子网号和广播地址之间的 IP 地址。(例如子网号 192.168.1.0 和广播地址 255.255.255.0 那么范围是 192.168.1.1 直到 192.168.1.254)。

要在 PHP 中实现这一点,您必须基本上按照我对上面有趣的八位字节所做的操作(不计算 1),然后http://php.net/manual/en/language.operators.bitwise.php在每个相应的八位字节中使用按位运算符。希望这可以帮助。

于 2013-08-27T19:06:35.740 回答