function ip_address_to_number($IPaddress) {
if(!$IPaddress) {
return false;
} else {
$ips = split('\.',$IPaddress);
return($ips[3] + $ips[2]*256 + $ips[1]*65536 + $ips[0]*16777216);
}
}该函数执行与php捆绑函数ip2long相同的代码。然而,当我打印这两个值时,我得到了两个不同的结果。为什么?(我在wamp环境中使用php 5.2.10 )。
ip2long('200.117.248.17'); //returns **-931792879**
ip_address_to_number('200.117.248.17'); // returns **3363174417**发布于 2010-06-17 23:06:07
试着这样做:
$ip = sprintf('%u', ip2long($_SERVER['REMOTE_ADDR']));然后,sprintf将把它写成一个无符号整数。
发布于 2010-06-17 23:12:09
$ips[3] = 17
+ $ips[2] * 256 = 248 * 256 = 63488
+ $ips[1] * 65536 = 117 * 65536 = 7667712
+ $ips[0] * 16777216 = 200 * 16777216 = 3355443200
= 3363174417PHP最大整数值(32位)为2147483647,小于3363174417
引用自ip2long() PHP手册页面
注意:由于PHP的整数类型是有符号的,并且许多IP地址将产生负整数,因此您需要使用"%u“格式化程序sprintf()或printf()来获取无符号IP地址的字符串表示形式。
发布于 2013-04-08 23:29:29
你可以使用-
// IP Address to Number
function inet_aton($ip)
{
$ip = trim($ip);
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) return 0;
return sprintf("%u", ip2long($ip));
}
// Number to IP Address
function inet_ntoa($num)
{
$num = trim($num);
if ($num == "0") return "0.0.0.0";
return long2ip(-(4294967295 - ($num - 1)));
}https://stackoverflow.com/questions/3062843
复制相似问题