PHP的ip2long 是将IP地址转换为数值的函数。
ip2long() 转出来的数值应该都是正整数,但是在某些机器转出负数, 刚开始以为是 PHP 版本问题, 后来做些测试, 确定是系统版本 32bits 和 64bits 的问题。
32 bits ip2long(): -2147483648 ~ 214748364764 64 bits ip2long(): 0 ~ 42949672945
测试代码:
3
list(
$a
,
$b
,
$c
,
$d
) = split(
"."
,
$ip
);
4
$ip_long
= ((
$a
* 256 +
$b
) * 256 +
$c
) * 256 +
$d
;
另外做测试,在return值加上intval(), 如下述:
3
list(
$a
,
$b
,
$c
,
$d
) = split(
"."
,
$ip
);
4
$ip_long
= ((
$a
* 256 +
$b
) * 256 +
$c
) * 256 +
$d
;
5
return
intval
(
$ip_long
);
intval在32bits/64 bits最大值是不同的,于intval()里面有写到下述:
The maximum value depends on the system. 32 bit systems have a maximum signed integer range of -2147483648 to 2147483647. So for example on such a system, intval("1000000000000") will return 2147483647. The maximum signed integer value for 64 bit systems is 9223372036854775807.
另外做其它测试:
02
ip2long
(
"127.255.255.255"
);
03
ip2long
(
"255.255.255.255"
);
04
ip2long
(
"255.255.255.254"
);
05
ip2long
(
"192.168.1.2"
);
06
ip2long
() 于 64bits 的系统测试
07
ip2long
(
"127.255.255.255"
);
08
ip2long
(
"255.255.255.255"
);
09
ip2long
(
"255.255.255.254"
);
10
ip2long
(
"192.168.1.2"
);
解法1 - 自己转换
2
list(
$a
,
$b
,
$c
,
$d
) = split(
"."
,
$ip
);
3
return
((
$a
* 256 +
$b
) * 256 +
$c
) * 256 +
$d
;
解法2 - 转成二进制, 再转回十进制
3
echo
bindec
(
decbin
(
ip2long
(
"192.168.1.2"
)));
解法3 - 官方建议的解法 (推荐用此方法)
2
printf(
"%u"
,
ip2long
(
"192.168.1.2"
));
4
echo
sprintf(
"%u"
,
ip2long
(
"192.168.1.2"
));
[软件工程网 注],关于第一种方法,从数值转换回IP可以使用下面的参考代码:
1
function
longtoip(
$num
) {
3
$c
= ((
$num
-
$d
)/256)%256;
4
$b
= ((
$num
-(
$c
*256)-
$d
)/(256*256))%256;
5
$a
= ((
$num
-(
$b
*256*256)-
$c
*256-
$d
)/(256*256*256))%256;
6
return
$a
.
"."
.
$b
.
"."
.
$c
.
"."
.
$d
; }