search

Home  >  Q&A  >  body text

php 计算网络地址的bug

`<?php
function ipToLong($network)
{ $networkLong = '';
if(filter_var($network, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)){
$networkLong=base_convert(sprintf("%u",ip2long($network)), 10, 2);
}else{
$networkPack = inet_pton($network);

    $bits = 15;
    while ($bits >= 0) {
        $bin = sprintf("%08b", (ord($networkPack[$bits])));
        $networkLong = $bin.$networkLong;
        $bits--;
    }
}
    return $networkLong;

}
/获取网络地址/
function getSegment($network,$mask){
if(filter_var($network, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)){
$ipv4Long=ipToLong($network);
$maskLong=str_pad(str_repeat(1, $mask), 32, 0);
$segment=$ipv4Long & $maskLong;
return $segment;
}else{
$ipv6Long=ipToLong($network);
$maskLong=str_pad(str_repeat(1, $mask), 128, 0);
$segment=$ipv6Long & $maskLong;
return $segment;
}
}
echo ipToLong('106.32.59.244');
echo '
';
echo getSegment('106.32.59.244','29');
?> `
上面计算出来的网络地址就是106.32.59.244,为什么和下图计算出来的不一致呢?

迷茫迷茫2775 days ago834

reply all(1)I'll reply

  • PHP中文网

    PHP中文网2017-04-10 15:46:18

    因为和你机器是32位还是64位有关系~

    reply
    0
  • Cancelreply