解决PHP中long2ip反序的问题

原因是:php中没有考虑主机序和网络序的转换,导致主机序为little-endian的机器上,long2ip()得到的IP反了。

下面是解决办法,我们自己判断little-endian和big-endian:

[php]
function long2ip_fix($ip_32)
{
$ip = long2ip($ip_32);
//先判断是big-endian还是little-endian
$foo = 0x3456789a;
switch (pack (‘L’, $foo)) {

case pack (‘V’, $foo):
//little-endian
$tmp = split("\.",$ip);
$ip = $tmp[3].".".$tmp[2].".".$tmp[1].".".$tmp[0];
break;

case pack (‘V’, $foo):
//big-endian
//Nothing
break;
default:
}

return $ip;
}
[/php]

One thought on “解决PHP中long2ip反序的问题

  1. coder4Everhythm

    switch 的第二个 case 写错了…… 应该是’N’, case pack (‘N’, $foo):

    Reply

Leave a Reply

Your email address will not be published.