在 Python 中对 IPv6 地址和网络进行按位操作
Python3 具有易于使用的 ipaddress 库,提供许多计算。但是,地址没有按位布尔运算符。
这篇文章向你展示如何对 IPv6Address() 对象执行按位操作。我们将使用以下策略:
- 使用
.packed获取 IP 地址的二进制 bytes() 实例 - 使用
int.from_bytes()获取表示二进制地址的整数 - 使用该整数执行按位操作
- 使用
result.to_bytes(16, ...)将整数转换回正确字节顺序的bytes()数组 - 从结果字节数组构造
IPv6Address()对象。
Python 代码:
bitwise_ipv6_utils.py
import ipaddress
def bitwise_and_ipv6(addr1, addr2):
result_int = int.from_bytes(addr1.packed, byteorder="big") & int.from_bytes(addr2.packed, byteorder="big")
return ipaddress.IPv6Address(result_int.to_bytes(16, byteorder="big"))
def bitwise_or_ipv6(addr1, addr2):
result_int = int.from_bytes(addr1.packed, byteorder="big") | int.from_bytes(addr2.packed, byteorder="big")
return ipaddress.IPv6Address(result_int.to_bytes(16, byteorder="big"))
def bitwise_xor_ipv6(addr1, addr2):
result_int = int.from_bytes(addr1.packed, byteorder="big") ^ int.from_bytes(addr2.packed, byteorder="big")
return ipaddress.IPv6Address(result_int.to_bytes(16, byteorder="big"))示例用法:
bitwise_ipv6_example.py
a = ipaddress.IPv6Address('2001:16b8:2703:8835:9ec7:a6ff:febe:96b1')
b = ipaddress.IPv6Address('2001:16b8:2703:4241:9ec7:a6ff:febe:96b1')
print(bitwise_and_ipv6(a, b)) # IPv6Address('2001:16b8:2703:1:9ec7:a6ff:febe:96b1')
print(bitwise_or_ipv6(a, b)) # IPv6Address('2001:16b8:2703:ca75:9ec7:a6ff:febe:96b1')
print(bitwise_xor_ipv6(a, b)) # IPv6Address('0:0:0:ca74::')类似地,你可以使用此代码来操作 IPv6Network() 实例:
bitwise_ipv6_network_example.py
a = ipaddress.IPv6Network('2001:16b8:2703:8835:9ec7:a6ff:febe::/112')
b = ipaddress.IPv6Network('2001:16b8:2703:4241:9ec7:a6ff:febe::/112')
print(bitwise_and_ipv6(a.network_address, b.network_address)) # IPv6Address('2001:16b8:2703:1:9ec7:a6ff:febe:0')
print(bitwise_or_ipv6(a.network_address, b.network_address)) # IPv6Address('2001:16b8:2703:ca75:9ec7:a6ff:febe:0')
print(bitwise_xor_ipv6(a.network_address, b.network_address)) # IPv6Address('0:0:0:ca74::')注意返回类型始终是 IPv6Address() 而不是 IPv6Network(),因为按位操作的结果没有关联的网络掩码。
除了 .network_address,你还可以使用 IPv6Address() 实例的其他属性,如 .broadcast_address 或 .hostmask 或 .netmask。
Check out similar posts by category:
Networking, Python
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow