如何在Python中将IPv6链路本地地址转换为MAC地址

时间:2016-05-10 14:03:37

标签: python python-2.7 type-conversion ipv6 mac-address

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

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

使用Python进入MAC-Adress。所以输出应该是

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

就像在此页面上一样:the camel JPA documentation 如何将IPV6转换为MAC?

1 个答案:

答案 0 :(得分:9)

以下是两种可以双向转换的功能。

检查给定的参数是否是正确的MAC或IPv6可能也很有用。

从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