Skip to main content
 首页 » 编程设计

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

2025年05月04日12落叶无声

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

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

使用 Python 转换为 MAC 地址。所以输出应该是

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

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

请您参考如下方法:

这里有两个函数可以进行两种方式的转换。

检查给定参数是否为正确的 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