【问题标题】:How to convert IPv6 link-local address to MAC address in Python如何在 Python 中将 IPv6 链接本地地址转换为 MAC 地址
【发布时间】:2016-05-10 14:03:36
【问题描述】:

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

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

使用 Python 进入 MAC 地址。所以输出应该是

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

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

【问题讨论】:

  • 这些步骤记录在ben.akrin.com/?p=1347
  • RFC4941 让这有点没用。
  • 该地址 fe80::1d81:b870:163c:5845 不是从 MAC 地址生成的 IPv6 地址。从 MAC 地址生成的 IPv6 地址将在地址的接口 ID 部分的中间有 ff:fe,但该地址在那里有 70:16。您拥有的是使用隐私扩展或随机生成的地址。

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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-18
    • 1970-01-01
    • 2011-02-16
    • 1970-01-01
    • 2018-12-26
    • 1970-01-01
    • 2013-05-09
    • 2013-11-14
    相关资源
    最近更新 更多