Home > Backend Development > PHP Tutorial > Solution to the problem of IPV6 ip2long in php_PHP tutorial

Solution to the problem of IPV6 ip2long in php_PHP tutorial

WBOY
Release: 2016-07-13 10:57:33
Original
1406 people have browsed it

On 32-bit systems, ip2long cannot convert IPv6, but you can convert ip2bin and bin2ip This function converts to IPv4 and IPv6, returning false if it is invalid

Instance program

The code is as follows
 代码如下 复制代码

function ip2bin($ip)
{
if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false)
return base_convert(ip2long($ip),10,2);
if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === false)
return false;
if(($ip_n = inet_pton($ip)) === false) return false;
$bits = 15; // 16 x 8 bit = 128bit (ipv6)
while ($bits >= 0)
    {
        $bin = sprintf("%08b",(ord($ip_n[$bits])));
        $ipbin = $bin.$ipbin;
        $bits--;
    }
    return $ipbin;
}


function bin2ip($bin)
{
   if(strlen($bin) <= 32) // 32bits (ipv4)
return long2ip(base_convert($bin,2,10));
if(strlen($bin) != 128)
return false;
$pad = 128 - strlen($bin);
for ($i = 1; $i <= $pad; $i++)
{
$bin = "0".$bin;
}
$bits = 0;
while ($bits <= 7)
{
$bin_part = substr($bin,($bits*16),16);
$ipv6 .= dechex(bindec($bin_part)).":";
$bits++;
}
return inet_ntop(inet_pton(substr($ipv6,0,-1)));
}
?>

Copy code
function ip2bin($ip)
{
If(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false)
          return base_convert(ip2long($ip),10,2);
If(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === false)
         return false;
If(($ip_n = inet_pton($ip)) === false) return false;
$bits = 15; // 16 x 8 bit = 128bit (ipv6)
While ($bits >= 0)
{
         $bin = sprintf("%08b",(ord($ip_n[$bits])));
$ipbin = $bin.$ipbin;
         $bits--;
}  
Return $ipbin;
}


function bin2ip($bin)
{
if(strlen($bin) <= 32) // 32bits (ipv4)
         return long2ip(base_convert($bin,2,10));
if(strlen($bin) != 128)
        return false;
$pad = 128 - strlen($bin);
for ($i = 1; $i <= $pad; $i++)
{
         $bin = "0".$bin;
}
$bits = 0;
while ($bits <= 7)
{
$bin_part = substr($bin,($bits*16),16);
         $ipv6 .= dechex(bindec($bin_part)).":";
$bits++;
}
Return inet_ntop(inet_pton(substr($ipv6,0,-1)));
}
?>

http://www.bkjia.com/PHPjc/632086.htmlwww.bkjia.com
true
http: //www.bkjia.com/PHPjc/632086.html
TechArticleIn 32-bit systems, ip2long cannot convert IPv6, but you can convert ip2bin and bin2ip this function to IPv4 and IPv6 , return false, if it is an invalid instance program code, copy the code as follows...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template