比较子网是否在IP范围内(在Python中)? [英] Compare if subnet is in IP range, in Python?

查看:584
本文介绍了比较子网是否在IP范围内(在Python中)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在csv文件中有一组带有标签说明的子网。我需要将这些描述分配给这些子网在另一个csv文件中所属的数据探测范围。

I have a set of subnets with labeled descriptions in a csv file. I need to assign these descriptions to the Data Probe ranges that these subnets belong to in another csv file.

给出一个IP地址 34.0.0.0 和子网掩码 255.255.0.0 的子网

Given a subnet with an ipaddress 34.0.0.0 and netmask 255.255.0.0,
I want to check if the subnet is in the range 34.163.83.230-34.163.83.230

我已经考虑过从子网的ip和网络掩码创建一个范围,并将其与Data Probe范围进行比较。我无法找出是否会产生正确的答案。

I have considered creating a range from the subnet's ip and net mask and comparing it to the Data Probe ranges. I haven't been able to find out if this would yield the correct answer.

我无法使用最新版本的Python(这必须与运行python的应用程序配合使用2.7),因此 ipaddress 模块对我来说不是一个选择。

I cannot use the latest version of Python (this has to work with an application running python 2.7), so the ipaddress module is not an option for me.

推荐答案

socket 模块提供了 inet_aton ,它将您的地址转换为位串。然后,您可以使用 struct.unpack 将其转换为整数,使用& 进行掩码,并使用整数比较:

The socket module provides inet_aton, which will convert your addresses to bitstrings. You can then convert them to integers using struct.unpack, mask using &, and use integer comparison:

from socket import inet_aton
from struct import unpack

def atol(a):
    return unpack(">L", inet_aton(a))[0]

addr = atol("30.44.230.0")
mask = atol("255.255.0.0")
lo = atol("32.44.230.0")
hi = atol("32.44.230.255")
prefix = addr & mask

print lo <= prefix <= hi 

这篇关于比较子网是否在IP范围内(在Python中)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆