python - 如何从 IP 地址中删除最后几位

标签 python ip-address

如何在 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/

相关文章:

python - 对于具有标准用户模型的具有外键的模型,RelatedObjectDoesNotExist

python - 如何更新 Django 中的多对多字段?

python - Django:来自调试页面的 ascii 回溯 (HTML)

Python 正则表达式匹配 IP 地址与/CIDR

c++ - ->h_addr_list[0] 是我需要的地址吗?

android - 在 Android 客户端设备上访问热点设备的 IP 地址

python - 在 Google Colab/Jupyter Notebook 中进行条件 pip 安装

python - 使用 rpy2 从 python 调用 R 脚本

python - numpy:将任意函数应用于数组元素

python - 将 IP 地址散列为 [0, H) 中的数字