Tag Archives: long2ip

PHP IPv6 ip2long und long2ip Funktionen

php bietet aktuell ip2long() und long2ip() nur für IPv4 an, für IPv6 gibt es aktuell soweit ich weiss noch keine native Funktionen, deshalb hier meine zwei Funktionen um ip2long und long2ip auch für IPv6 zu verwenden – diese Funktionen benötigen die php gmp-lib, unter Debian: apt-get install php5-gmp:

$ipv6 = “2001:4860:a005::68”;
function ip2long6($ipv6) {
$ip_n = inet_pton($ipv6);
$bits = 15; // 16 x 8 bit = 128bit
while ($bits >= 0) {
$bin = sprintf(“%08b”,(ord($ip_n[$bits])));
$ipv6long = $bin.$ipv6long;
$bits–;
}
return gmp_strval(gmp_init($ipv6long,2),10);
}

function long2ip6($ipv6long) {

$bin = gmp_strval(gmp_init($ipv6long,10),2);
if (strlen($bin) < 128) {
$pad = 128 – strlen($bin);
for ($i = 1; $i <= $pad; $i++) {
$bin = “0”.$bin;
}
}
$bits = 0;
while ($bits <= 7) {
$bin_part = substr($bin,($bits*16),16);
$ipv6 .= dechex(bindec($bin_part)).”:”;
$bits++;
}
// compress

return inet_ntop(inet_pton(substr($ipv6,0,-1)));
}

print $ipv6long =  ip2long6($ipv6).”\n”;
print $ipv6 = long2ip6($ipv6long).”\n”;

Ergebnis:

42541956150894553250710573749450571880
2001:4860:a005::68