首先:你为什么要关心地址是怎么写的?inet_pton() 将为您解析所有变体并为您提供一致的结果,然后您可以将其转换为二进制、十六进制或任何您想要的。
所有用于转换之类的代码::192.168.0.1
实际上0000:0000:0000:0000:0000:0000:c0a8:0001
都在我的帖子中。这正是我的示例函数所做的。
如果您0000:0000:0000:0000:0000:0000:192.168.0.1
先输入 inet_pton(),然后再输入 inet_ntop(),您将获得规范的 IPv6 表示法,::192.168.0.1
在这种情况下就是这样。如果该字符串以开头::
并且其余包含 no:
和三个点,那么您可以确定它是 IPv4 地址;-)
要将上一个问题的答案与此问题相结合:
function expand_ip_address($addr_str) {
/* First convert to binary, which also does syntax checking */
$addr_bin = @inet_pton($addr_str);
if ($addr_bin === FALSE) {
return FALSE;
}
$addr_hex = bin2hex($addr_bin);
/* See if this is an IPv4-Compatible IPv6 address (deprecated) or an
IPv4-Mapped IPv6 Address (used when IPv4 connections are mapped to
an IPv6 sockets and convert it to a normal IPv4 address */
if (strlen($addr_bin) == 16
&& substr($addr_hex, 0, 20) == str_repeat('0', 20)) {
/* First 80 bits are zero: now see if bits 81-96 are either all 0 or all 1 */
if (substr($addr_hex, 20, 4) == '0000')
|| substr($addr_hex, 20, 4) == 'ffff')) {
/* Remove leading bits so only the IPv4 bits remain */
$addr_bin = substr($addr_hex, 12);
}
}
/* Then differentiate between IPv4 and IPv6 */
if (strlen($addr_bin) == 4) {
/* IPv4: print each byte as 3 digits and add dots between them */
$ipv4_bytes = str_split($addr_bin);
$ipv4_ints = array_map('ord', $ipv4_bytes);
return vsprintf('%03d.%03d.%03d.%03d', $ipv4_ints);
} else {
/* IPv6: print as hex and add colons between each group of 4 hex digits */
return implode(':', str_split($addr_hex, 4));
}
}