On a replacement alternative for inet_pton() in PHP, the following code is given:
<?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;
}
?>
But when testing this using the following test code, it shows that not all entries are correct:
<?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
*/
?>
I don’t know about the correct IPv6 syntax, so I prefer if someone else, who knows more about IPv6 and standards, looks at this and tells me what’s wrong with it?
This code will do it right:
Results: