Title says it all. I already "did" this for IPv4;
$ip = '127.0.0.1'; // example
$ip = explode('.',$ip);
if( count($ip) != 4 ) $ip = array(0,0,0,0); // wrong ip format, default to 0.0.0.0
return chr($ip[0]) . chr($ip[1]) . chr($ip[2]) . chr($ip[3]);
I need to do the above for IPv6 as well. Reading through the IPv6 spec, (I admit I didn't read all of it), I saw several oddities ("exceptions") such as a set of 0 could be compressed to a double colon: ":0000:0000"=>"::" (if my understanding was correct). I also saw how you can have an IPv4-style string inside an IPv6 string: 0:0:0:0:0:0:127.0.0.1
Let's start by saying I've no freakin idea where to start. Help? :)
Thanks to Alvaro, now I've got a pure-PHP implementation of inet_pton:
/**
* @copyright 2004-2007 Aidan Lister <[email protected]>, Arpad Ray <[email protected]>
* @link http://php.net/inet_pton
* @author Arpad Ray <[email protected]>
*/
function php_compat_inet_pton($address) {
$r = ip2long($address);
if ($r !== false && $r != -1) return pack('N', $r);
$delim_count = substr_count($address, ':');
if ($delim_count < 1 || $delim_count > 7) return false;
$r = explode(':', $address);
$rcount = count($r);
if (($doub = array_search('', $r, 1)) !== false) {
$length = (!$doub || $doub == $rcount - 1 ? 2 : 1);
array_splice($r, $doub, $length, array_fill(0, 8 + $length - $rcount, 0));
}
$r = array_map('hexdec', $r);
array_unshift($r, 'n*');
$r = call_user_func_array('pack', $r);
return $r;
}
Problem is, I can't quite understand what it's doing. The issue is, I can't just use such a function since (for one thing) I know it's packing the IP in a differnt format than I'm doing (or want to).