首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将IPv6链接本地地址转换为MAC地址

如何将IPv6链接本地地址转换为MAC地址
EN

Stack Overflow用户
提问于 2016-05-10 14:03:36
回答 1查看 8.5K关注 0票数 3

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

代码语言:javascript
复制
fe80::1d81:b870:163c:5845 

和Python一起进入MAC区。所以输出应该是

代码语言:javascript
复制
 1f:81:b8:3c:58:45

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-05-19 07:24:55

以下是两种方式转换的两个函数。

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

从MAC到IPv6

代码语言:javascript
复制
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

代码语言:javascript
复制
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)

示例

代码语言:javascript
复制
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
票数 13
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37140846

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档