在 PHP 中 inet_pton()的替代方案中,给出了以下代码:
<?php
function inet_pton($ip)
{
# ipv4
if (strpos($ip, '.') !== FALSE) {
$ip = pack('N',ip2long($ip));
}
# ipv6
elseif (strpos($ip, ':') !== FALSE) {
$ip = explode(':', $ip);
$res = str_pad('', (4*(8-count($ip))), '0000', STR_PAD_LEFT);
foreach ($ip as $seg) {
$res .= str_pad($seg, 4, '0', STR_PAD_LEFT);
}
$ip = pack('H'.strlen($res), $res);
}
return $ip;
}
?>
但是当使用以下测试代码对此进行测试时,它表明并非所有条目都是正确的:
<?php
$arrIPs = array(
"2001:0db8:85a3:0000:0000:8a2e:0370:7334",
"fe80:01::af0",
"::af0",
"192.168.0.1",
"0000:0000:0000:0000:0000:0000:192.168.0.1");
foreach($arrIPs as $strIP) {
$strResult = bin2hex(inet_pton($strIP));
echo "From: {$strIP} to: {$strResult}<br />\n";
}
/*
From: 2001:0db8:85a3:0000:0000:8a2e:0370:7334 to: 20010db885a3000000008a2e03707334
From: fe80:01::af0 to: 0000000000000000fe80000100000af0 //Incorrect
From: ::af0 to: 00000000000000000000000000000af0
From: 192.168.0.1 to: c0a80001
From: 0000:0000:0000:0000:0000:0000:192.168.0.1 to: 00000000 //Incorrect
*/
?>
我不知道正确的 IPv6 语法,所以我更喜欢其他更了解 IPv6 和标准的人,看看这个并告诉我它有什么问题?