Skip to content

Instantly share code, notes, and snippets.

@gsdevme
Created April 2, 2012 04:52
Show Gist options
  • Save gsdevme/2280841 to your computer and use it in GitHub Desktop.
Save gsdevme/2280841 to your computer and use it in GitHub Desktop.
Shit for handling IPv6 & mysql storage
<?php
/**
* Shit for handling IPv6 & mysql storage, @gsphpdev
* Bloody headache... remember this Gavin!
*/
/**
* Only PHP 5.4+ has this function so need to add one if not
*/
if(!function_exists('hex2bin')){
function hex2bin($hex)
{
return pack("H*" , $hex);
}
}
// Raw IPs
$ipv6 = '2001:0db8:85a3:0000:0000:8a2e:0370:7334';
$ipv4 = '193.155.066.001';
// This can be stored within MYSQL as varbinary(32)
$packedv6 = bin2hex(inet_pton($ipv6));
$packedv4 = bin2hex(inet_pton($ipv4));
$unpackedv6 = inet_ntop(hex2bin($packedv6));
$unpackedv4 = inet_ntop(hex2bin($packedv4));
echo '<pre>' . print_r($unpackedv6, true) . '</pre>';
echo '<pre>' . print_r($unpackedv4, true) . '</pre>';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment