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

iMa*_*Max 1 python mac-address type-conversion ipv6 python-2.7

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

fe80::1d81:b870:163c:5845 
Run Code Online (Sandbox Code Playgroud)

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

 1f:81:b8:3c:58:45
Run Code Online (Sandbox Code Playgroud)

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

sno*_*odo 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
Run Code Online (Sandbox Code Playgroud)

从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)
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)