检查IP是否在Python的CIDR范围内 [英] check if an IP is within a range of CIDR in Python

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

问题描述

我知道这里也有一些类似的问题,但是他们大多是想找到范围本身(它使用了一些库,例如stackoverflow所说的例子是我的问题的重复),并且是另一种语言.

I know there are some similar questions up here, but they mostly either want to find the range itself (which uses some libraries, like the example that stackoverflow says is a dupe of my question) and is in another language.

我有一种方法可以将子网转换为子网中ip范围的开头和结尾(好的,措辞不好,就像1.1.1.1/16 -> (1.1.0.0 , 1.1.255.255)一样)

I have a way to convert the subnet into the beginning and the end of the range of ip's in a subnet (okay, bad wording, it's simply like1.1.1.1/16 -> (1.1.0.0 , 1.1.255.255))

我现在要检查1.1.2.2是否在此子网内.我可以简单地通过><进行比较吗?

I now want to check if 1.1.2.2 is within this subnet. Can I simply do a > and < to compare?

ip_range = ('1.1.0.0', '1.1.255.255')
if '1.1.2.2' >= ip_range[0] and '1.1.2.2' <= ip_range[1]:
     return True

当我对其进行测试时,它可以工作,但是我不知道它是否对任何ipv4 ip都可以正常工作.我以为我只是比较ASCII顺序,所以这应该一直有效,但是有没有例外?

When I tested it, it works, but I don't know if it would always work for any ipv4 ip's. I'd assume I'm just comparing ASCII order , so this should always work, but is there any exception?

推荐答案

您真的不能在点分隔的数字列表上进行字符串比较,因为您的测试只会在输入1.1.99.99时失败,因为'9'很简单大于'2'

You can't really do string comparisons on a dot separated list of numbers because your test will simply fail on input say 1.1.99.99 as '9' is simply greater than '2'

>>> '1.1.99.99' < '1.1.255.255'
False

因此,您可以通过理解表达式将输入转换为整数元组

So instead you can convert the input into tuples of integers through comprehension expression

def convert_ipv4(ip):
    return tuple(int(n) for n in ip.split('.'))

请注意,没有类型检查,但是如果您输入的是正确的IP地址,那就可以了.由于您拥有2个元组的IP地址,因此您可以创建一个将开始和结束都作为参数的函数,将该元组传递到参数列表中,然后仅用一条语句返回它(因为Python允许链接比较).也许像这样:

Note the lack of type checking, but if your input is a proper IP address it will be fine. Since you have a 2-tuple of IP addresses, you can create a function that takes both start and end as argument, pass that tuple in through argument list, and return that with just one statement (as Python allows chaining of comparisons). Perhaps like:

def check_ipv4_in(addr, start, end):
    return convert_ipv4(start) < convert_ipv4(addr) < convert_ipv4(end)

测试一下.

>>> ip_range = ('1.1.0.0', '1.1.255.255')
>>> check_ipv4_in('1.1.99.99', *ip_range)
True

使用此方法,您可以将其延迟扩展到IPv6,尽管将需要向十六进制(而不是int)进行转换.

With this method you can lazily expand it to IPv6, though the conversion to and from hex (instead of int) will be needed instead.

这篇关于检查IP是否在Python的CIDR范围内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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