簡體   English   中英

如何將MAC地址轉換為IPv6鏈接本地地址,反之亦然

[英]How to convert MAC address into IPv6 link local address and vice-versa

將IPv6鏈接本地地址(例如,從廣播ping)轉換為mac地址通常會很有幫助。 將已知的mac地址轉換為fe80 ::-IPv6-address還可用於連接到具有已知物理地址的特定設備。

如何(在PHP中)將具有MAC地址的字符串轉換為fe80-Link本地地址,反之亦然?

所需的算法在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"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM