function mask2cidr($mask)
{
$long = ip2long($mask);
$base = ip2long('255.255.255.255');
return 32-log(($long ^ $base)+1,2);
/* xor-ing will give you the inverse mask,
log base 2 of that +1 will return the number
of bits that are off in the mask and subtracting
from 32 gets you the cidr notation */
}
2 回答
复杂的方法是将网络掩码转换为二进制并计算前导1位的数量 . 但由于只有33个可能的值,更简单的方法只是一个关联数组:
有点坚持主题,但可能会帮助别人,你在这里有解决方案:
PHP ip2long help