python - 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.)
解决方案
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
推荐阅读
- java - org.mockito.exceptions.misusing.InvalidUseOfMatchersException' 异常
- c# - 限制来自 API 的 JSON 字符串响应以选择属性
- user-management - 通过 PI 获取云身份的消费者帐户
- c - 从 C 中的文件中读取特定的行和列
- ios - 设备锁定/空闲时,Goggle chromecast cast 自动播放不起作用
- javascript - 我必须使用 JSZip 创建不同的 zip 文件。是否可以将它们合并到一个档案中?
- python - 根据“如果”逻辑将列添加到末尾
- matplotlib - 鼠标悬停仅在实际数据点上
- python-3.x - anaconda/Jupyter notebook 上的 Python 不响应“import tensorflow”(无错误)
- javascript - 多个重叠矩形的边界框