Skip to content

Commit

Permalink
use shorter network prefix
Browse files Browse the repository at this point in the history
  • Loading branch information
dantheta committed Oct 18, 2021
1 parent 8090301 commit 5322bc5
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 17 deletions.
25 changes: 12 additions & 13 deletions api/1.2/libs/services.php
Original file line number Diff line number Diff line change
Expand Up @@ -464,25 +464,24 @@ function write_cache($ip, $network) {
}

function normalize_ipv6($ip) {
// normalize address to full 128 bits, returned as array of chars
// normalize address to shorter network prefix
$words = explode(':', $ip);

// find empty segment denoting '::'
$dblpos = array_search("", $words);
if ($dblpos !== false) {
// eliminate run of zeros and everthing after
$words = array_slice($words, 0, $dblpos);
}

foreach ($words as &$w) {
if ($w == "") {
continue;
}
elseif (strlen($w) < 4) {
// pad each segment with leading zeros
if (strlen($w) < 4) {
$w = str_pad($w, 4, "0", STR_PAD_LEFT);
}
}
if (count($words) < 8) {
$i = array_search("", $words);
$keep = array_slice($words, 0, $i);
$keepend = array_slice($words, $i+1);
$add = array_fill(0, 7-$i, "0000");
$words = array_merge($keep, $add, $keepend);
}

# flatten to single list
# flatten to single string
$ipstr = join("", $words);
return $ipstr;
}
Expand Down
10 changes: 6 additions & 4 deletions tests/ip.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@

$service = new IpLookupService(null);

$test = $service->normalize_ipv6("2a02:8011:4003:1001::11");
assert($test == "2a028011400310010000000000000011");
$test = $service->normalize_ipv6("2a02:8011:4003:1:1::11");
assert($test == "2a028011400300010001000000000011");
$test = $service->normalize_ipv6("2a02:8011:4003:0b01::11");
print($test . "\n");
assert($test == "2a02801140030b01");
$test = $service->normalize_ipv6("2a02:8011:4003:1:b1::11");
print($test . "\n");
assert($test == "2a0280114003000100b1");

0 comments on commit 5322bc5

Please sign in to comment.