如何将 IPv6 link-本地地址转换为 Python 中的 MAC 地址

How to convert IPv6 link-local address to MAC address in Python

我正在寻找一种转换 IPV6 地址的方法,例如

fe80::1d81:b870:163c:5845 

进入一个 MAC-地址 Python。所以输出应该是

 1f:81:b8:3c:58:45

就像这个页面上的一样:http://ben.akrin.com/?p=4103 如何将 IPV6 转换为 MAC?

这里有两个函数可以双向转换。

检查给定参数是否正确 MACs 或 IPv6s 可能也很有用。

从MAC到IPv6

def mac2ipv6(mac):
    # only accept MACs separated by a colon
    parts = mac.split(":")

    # modify parts to match IPv6 value
    parts.insert(3, "ff")
    parts.insert(4, "fe")
    parts[0] = "%x" % (int(parts[0], 16) ^ 2)

    # format output
    ipv6Parts = []
    for i in range(0, len(parts), 2):
        ipv6Parts.append("".join(parts[i:i+2]))
    ipv6 = "fe80::%s/64" % (":".join(ipv6Parts))
    return ipv6

从 IPv6 到 MAC

def ipv62mac(ipv6):
    # remove subnet info if given
    subnetIndex = ipv6.find("/")
    if subnetIndex != -1:
        ipv6 = ipv6[:subnetIndex]

    ipv6Parts = ipv6.split(":")
    macParts = []
    for ipv6Part in ipv6Parts[-4:]:
        while len(ipv6Part) < 4:
            ipv6Part = "0" + ipv6Part
        macParts.append(ipv6Part[:2])
        macParts.append(ipv6Part[-2:])

    # modify parts to match MAC value
    macParts[0] = "%02x" % (int(macParts[0], 16) ^ 2)
    del macParts[4]
    del macParts[3]

    return ":".join(macParts)

例子

ipv6 = mac2ipv6("52:74:f2:b1:a8:7f")
back2mac = ipv62mac(ipv6)
print "IPv6:", ipv6    # prints IPv6: fe80::5074:f2ff:feb1:a87f/64
print "MAC:", back2mac # prints MAC: 52:74:f2:b1:a8:7f