首页 > 解决方案 > Convert a string (without separators) into IPV6 address representation

问题描述

I'm trying to get the local IPV6 address by reading /proc/net/if_inet6. But the address there is without any colons like: 000000000000000000000abc00070def.

So I'm adding colons (:) at multiple places like this:

str6 = "000000000000000000000abc00070def"
i = 4
addr = str6[:i]
while i < len(str6):
    addr += ":" + str6[i:i+4]
    i += 4
print addr     # output: 0000:0000:0000:0000:0000:0abc:0007:0def

For a normal string this is working fine.

But since the string is a IPV6 address, so wondering is there a better way to do it? (Tried with ipaddress module but I don't think it supports without colons.)

标签: pythonip-addressipv6

解决方案


ipaddress.IPv6Address还可以从“有效”整数构造 IPv6 地址:

import ipaddress

ipv6_addr = ipaddress.ip_address(int('000000000000000000000abc00070def', 16))
print(ipv6_addr)

印刷:

::abc:7:def

地址表示的长形式(exploded):

print(ipv6_addr.exploded)

印刷:

0000:0000:0000:0000:0000:0abc:0007:0def

推荐阅读