Last active
April 29, 2018 03:46
-
-
Save chitoku-k/78e2d584a46d05c2225dcf8cf28c711d to your computer and use it in GitHub Desktop.
MAP-E のアドレス変換器(PHP >= 7.1.0)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// https://qiita.com/mpyw/items/0fdffd3c70b3abd802f5 | |
function array_group_by_range(array $array, $separator = '-') | |
{ | |
sort($array, SORT_NUMERIC); | |
$pairs = $ranges = []; | |
foreach (array_values(array_unique($array, SORT_NUMERIC)) as $i => $v) { | |
$pairs[$v - $i][isset($pairs[$v - $i])] = $v; | |
} | |
foreach ($pairs as $pair) { | |
$ranges[] = implode($separator, $pair); | |
} | |
return $ranges; | |
} | |
// MAP-E IPv4 | |
function calculate_mapped_ipv4(string $ipv6) | |
{ | |
static $address_map = [ | |
'240b:10' => '106.72', | |
'240b:12' => '14.8', | |
'240b:250' => '14.10', | |
'240b:252' => '14.12', | |
]; | |
preg_match('/^(240b:[a-f0-9]{1,4}):([a-f0-9]{2})([a-f0-9]{2})/', $ipv6, $matches); | |
[ , $key, $high_1, $high_2 ] = $matches; | |
return sprintf('%s.%s.%s', $address_map[$key], intval($high_1, 16), intval($high_2, 16)); | |
} | |
// CE IPv6 | |
function calculate_ce_ipv6(string $ipv6) | |
{ | |
preg_match('/^(240b:[a-f0-9]{1,4}):([a-f0-9]{1,4}):([a-f0-9]{1,4})/', $ipv6, $matches); | |
[ , $key, $high, $low ] = $matches; | |
$ipv4 = sprintf('%x:%x%02x:%02x', ...array_map('intval', explode('.', calculate_mapped_ipv4($ipv6)))); | |
return sprintf('%s:%s:%s:%s00:%s', $key, $high, $low, $ipv4, $low); | |
} | |
// MAP-E Ports | |
function calculate_mapped_ports(string $ipv6) | |
{ | |
preg_match('/^240b:[a-f0-9]{1,4}:([a-f0-9]{2})/', $ipv6, $matches); | |
[ , $psid ] = $matches; | |
return array_merge(...array_map(function ($port) use ($psid) { | |
[ $high, $low ] = str_split(sprintf('%02x', $port)); | |
return [ | |
sprintf('%02x', $port) => intval(sprintf('%s%s%s', $high, $psid, $low), 16), | |
]; | |
}, range(0x10, 0xff))); | |
} | |
echo 'IPv6: '; | |
$ipv6 = strtolower(rtrim(fgets(STDIN))); | |
echo "\n"; | |
echo "Mapped IPv4:\n " . calculate_mapped_ipv4($ipv6) . "\n"; | |
echo "CE IPv6:\n " . calculate_ce_ipv6($ipv6) . "\n"; | |
echo "Mapped ports:\n " . implode("\n ", array_group_by_range(calculate_mapped_ports($ipv6))) . "\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment