且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检查IP是否在Python的CIDR范围内

更新时间:2022-06-10 06:02:07

您真的不能在点分隔的数字列表上进行字符串比较,因为您的测试只会在输入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.