当前位置:Gxlcms > PHP教程 > php计算网络地址的bug

php计算网络地址的bug

时间:2021-07-01 10:21:17 帮助过:19人阅读

` 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,为什么和下图计算出来的不一致呢?

回复内容:

` 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,为什么和下图计算出来的不一致呢?

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

人气教程排行