gpt4 book ai didi

python - 如何从 ip 地址中删除最后一位

转载 作者:太空宇宙 更新时间:2023-11-04 01:29:48 27 4
gpt4 key购买 nike

如何在 Python 中将 IP 地址的最后 n 位清零?我更喜欢使用标准库的解决方案,很可能是 ipaddress .

一些 strip_addr 测试用例看起来像:

assert strip_addr(u'1.2.3.4', 24) == u'1.2.3.0'
assert strip_addr(u'2001:1234:f678::9', 33) == u'2001:1234:8000::'

最佳答案

如何使用 interface network objects

import ipaddress

def strip_addr(ip, bits):
nwif = ipaddress.ip_interface(u'%s/%s' % (ip, bits))
return str(nwif.network.network_address)

assert strip_addr(u'1.2.3.4', 24) == u'1.2.3.0'
assert strip_addr(u'2001:1234:f678::9', 33) == u'2001:1234:8000::'

关于python - 如何从 ip 地址中删除最后一位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14679198/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com