如何将MAC地址转换为IPv6链接本地地址,反之亦然

问题描述 投票:0回答:1

将IPv6链路本地地址(例如,从广播ping)转换为mac地址通常是有帮助的。将已知的mac地址转换为fe80 :: - IPv6地址对于连接具有已知物理地址的特定设备也很有用。

我如何(在PHP中)将具有MAC地址的字符串转换为fe80-Link本地地址,反之亦然?

php networking ipv6
1个回答
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"
© www.soinside.com 2019 - 2024. All rights reserved.