首页 >后端开发 >php教程 >php 计算网络地址的bug

php 计算网络地址的bug

WBOY
WBOY原创
2016-06-06 20:32:291140浏览

` 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);

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

}
/获取网络地址/
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,为什么和下图计算出来的不一致呢?

php 计算网络地址的bug

回复内容:

` 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);

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

}
/获取网络地址/
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,为什么和下图计算出来的不一致呢?

php 计算网络地址的bug

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

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn