我正在做一个需要扩展 IPv6 地址的项目。其他用户创建的功能并不多,而且现有的功能也很丑陋。其中一些包含多个
foreach
和 gmp_init
,这增加了很多开销并且更难维护代码。我需要一个简单、不费力的脚本来扩展 IPv6。
将此内容发布给社区。
以下是两行代码,其中
$ip
是压缩的 IPv6 地址。返回展开的$ip
。
示例:
$ip = "fe80:01::af0";
echo expand($ip); // fe80:0001:0000:0000:0000:0000:0000:0af0
功能:
function expand($ip){
$hex = unpack("H*hex", inet_pton($ip));
$ip = substr(preg_replace("/([A-f0-9]{4})/", "$1:", $hex['hex']), 0, -1);
return $ip;
}
在 Mike Mackintosh 和 Yann Milin 的帮助下,我想出了这个函数:
function expandIPv6(string $ip): string
{
$hex = bin2hex(inet_pton($ip));
return implode(':', str_split($hex, 4));
}
下面一个更通用的函数也将从 IPv4 映射的 IPv6 地址中提取 IPv4:
function expandIPv6(string $ip): string
{
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
return $ip;
}
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
$hex = bin2hex(inet_pton($ip));
return str_starts_with($hex, '00000000000000000000ffff')
// IPv4-mapped IPv6 addresses
? long2ip(hexdec(substr($hex, -8)))
: implode(':', str_split($hex, 4));
}
return "";
}