将IPv6链接本地地址(例如从广播ping)转换为mac地址通常会很有帮助。将已知的mac地址转换为fe80 ::-IPv6-address还可用于连接到具有已知物理地址的特定设备。
如何(在PHP中)将具有MAC地址的字符串转换为fe80-Link本地地址,反之亦然?
答案 0 :(得分:1)
所需的算法在RFC4291附录A中指定。 https://tools.ietf.org/html/rfc4291#appendix-A
这是PHP中的示例实现:
/**
* Converts a MAC-Address into the fe80:: IPv6 link local equivalent
*
* @param string $mac MAC-Address
*/
function macTov6LL(string $mac)
{
$mac = preg_replace('/[^a-f0-9]/', '', strtolower($mac));
$ll = substr($mac, 0, 1);
$ll .= dechex(hexdec(substr($mac, 1, 1)) ^ 2);
$ll .= substr($mac, 2, 4);
$ll .= "fffe";
$ll .= substr($mac, 6, 6);
$ll = wordwrap($ll, 4, ":", true);
return inet_ntop(inet_pton("fe80::" . $ll));
}
/**
* Converts a fe80:: IPv6 Link Local Address into a MAC-Address
*
* @param string $ipv6ll fe80:: Link Local Address
*/
function v6LLToMac(string $ipv6ll)
{
$ll = unpack("H*hex", inet_pton($ipv6ll))['hex'];
$mac = substr($ll, 16, 1);
$mac .= dechex(hexdec(substr($ll, 17, 1)) ^ 2);
$mac .= substr($ll, 18, 4);
$mac .= substr($ll, 26, 6);
return wordwrap($mac, 2, ":", true); ;
}
var_dump(macTov6LL("B8:27:EB:B9:E9:35"));
// results in: string(25) "fe80::ba27:ebff:feb9:e935"
var_dump(v6LLToMac("fe80::ba27:ebff:feb9:e935"));
// results in: string(17) "b8:27:eb:b9:e9:35"