在32位系统,ip2long不能转换IPv6,但您可以转换ip2bin和bin2ip,这个函数转换为IPv4和IPv6,返回false,如果是无效的,实例程序:
- <?php
- 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;
- while ($bits >= 0)
- {
- $bin = sprintf("%08b",(ord($ip_n[$bits])));
- $ipbin = $bin.$ipbin;
- $bits--;
- }
- return $ipbin;
- }
-
- function bin2ip($bin)
- {
- if(strlen($bin) <= 32)
- 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)));
- }
- ?>
|