检查Python3上的IP是否在网络中

2024-04-29 14:22:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试在两个列表上运行一个例程,这些列表来自MySQL查询-一个包含CIDR网络,另一个包含IP地址。我试图比较IP列表中的条目,看看它们是否在CIDR列表所描述的网络中,并对那些不在的网络中进行操作。在

我试图使用netaddr模块,但这似乎还没有在Python3上实现?在

我也尝试过使用ipaddress,但我似乎无法正确地比较它们。使用IP地址,我有以下代码:

networks = (('1.1.6.0/20',), ('2.8.2.0/19',), ('7.2.2.0/19',), ('2.2.0.0/19',))

ips = ((8888, 'customer', b'2.8.4.64', '8888*200'),(8888, 'customer', b'1.1.6.3', '8888*201'), (8888, 'customer', b'122.223.159.3', '8888*202'))

straglers = list()

for ip in ips:
    exclude = 0
    for network in networks:
        subnet = ip_network(network[0])
        if ip_address(ip[2]) in subnet:
            exclude = 1
    if exclude == 0:
        straglers.append([ip[3],ip[2],ip[1]]) # extension, customer_ip, company

按照目前的情况,代码给出的值错误如下:ValueError: b'82.148.47.64' does not appear to be an IPv4 or IPv6 address

我尝试过将ip[2]转换为utf-8字符串,但这没有什么区别。在


Tags: 代码inip网络列表forifnetwork
1条回答
网友
1楼 · 发布于 2024-04-29 14:22:06

你所描述的列表实际上是一个元组。在

首先,当我运行你的代码时,我没有收到你得到的错误

ValueError: b'82.148.47.64' does not appear to be an IPv4 or IPv6 address

相反,我收到了以下信息

raise ValueError('%s has host bits set' % self) ValueError: 1.1.6.0/20 has host bits set

这就是你实际收到的错误吗?如果是这样,这就是如何正确地纠正它。在

引用自IP地址模块Defining Networks

By default, attempting to create a network object with host bits set will result in ValueError being raised. To request that the additional bits instead be coerced to zero, the flag strict=False can be passed to the constructor:

这是因为主机位已设置,并且需要强制为零,如上面的文档所述。将以下标志传递给构造函数strict=False。在

例如。在

subnet = ip_network(network[0], strict=False) 

另外,在你的IP中包含在元组中只需要格式化为字符串。在

例如。在

^{pr2}$

或者以下内容将呈现给您。在

'ValueError: b'2.8.4.64' does not appear to be an IPv4 or IPv6 address'

完整的工作代码。在

from ipaddress import ip_network, ip_address
networks = (('1.1.6.0/20',), ('2.8.2.0/19',), ('7.2.2.0/19',), ('2.2.0.0/19',))

ips = ((8888, 'customer', b'2.8.4.64', '8888*200'),(8888, 'customer', b'1.1.6.3', '8888*201'), (8888, 'customer', b'122.223.159.3', '8888*202'))

straglers = list()

for ip in ips:
    exclude = 0
    for network in networks:
        subnet = ip_network(network[0], strict=False)  
        print(ip_address(ip[2].decode('utf-8')))
        print(subnet)
        if ip_address(ip[2].decode('utf-8')) in subnet:
            exclude = 1
    if exclude == 0:
        straglers.append([ip[3],ip[2],ip[1]]) # extension, customer_ip, company
print(straglers)  

相关问题 更多 >