在我的Python应用程序中,我有一个IP地址字符串数组,如下所示:
[
"50.28.85.81-140", // Matches any IP address that matches the first 3 octets, and has its final octet somewhere between 81 and 140
"26.83.152.12-194" // Same idea: 26.83.152.12 would match, 26.83.152.120 would match, 26.83.152.195 would not match
]
我安装了netaddr
虽然文档看起来很棒,但我无法绕过它。这一定非常简单 - 如何检查给定的IP地址是否与这些范围之一匹配?不需要特别使用netaddr
- 任何简单的Python解决方案都可以。
答案 0 :(得分:4)
想法是拆分IP并分别检查每个组件。
mask = "26.83.152.12-192"
IP = "26.83.152.19"
def match(mask, IP):
splitted_IP = IP.split('.')
for index, current_range in enumerate(mask.split('.')):
if '-' in current_range:
mini, maxi = map(int,current_range.split('-'))
else:
mini = maxi = int(current_range)
if not (mini <= int(splitted_IP[index]) <= maxi):
return False
return True
答案 1 :(得分:3)
不确定这是最优的,但这是基础python,不需要额外的包。
ip_range
,创建一个列表,其中包含1个元素(如果是简单值)和range
if范围。因此它创建了一个包含4个int / range对象的列表。zip
使用您的地址的split
版本并测试另一个范围内的每个值注意:使用range
可确保超快in
测试(在Python 3中)(Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3?)
ip_range = "50.28.85.81-140"
toks = [[int(d)] if d.isdigit() else range(int(d.split("-")[0]),int(d.split("-")[1]+1)) for d in ip_range.split(".")]
print(toks) # debug
for test_ip in ("50.28.85.86","50.284.85.200","1.2.3.4"):
print (all(int(a) in b for a,b in zip(test_ip.split("."),toks)))
结果(如预期):
[[50], [28], [85], range(81, 140)]
True
False
False