检查IP地址是否在给定范围内 [英] Checking if IP address lies within a given range
问题描述
我想检查IP 180.179.77.11
是否在特定范围内,例如180.179.0.0 - 180.179.255.255
.
I want to check if IP 180.179.77.11
lies between a particular range, say 180.179.0.0 - 180.179.255.255
.
我编写了一个函数,该函数将每个IP八位字节与其他八位字节进行比较.
I wrote a function which will compare every IP octet with the others.
def match(mask, IP):
min_ip = mask.split(' - ')[0].split('.')
max_ip = mask.split(' - ')[1].split('.')
ip = IP.split('.')
for i in range(4):
print ip[i] + " < " + min_ip[i] + " or " + ip[i] + " > " + max_ip[i]
print ip[i] < min_ip[i] or ip[i] > max_ip[i]
if ip[i] < min_ip[i] or ip[i] > max_ip[i]:
return False
return True
match("180.179.0.0 - 180.179.255.255", "180.179.77.11")
输出:
180 < 180 or 180 > 180
False
179 < 179 or 179 > 179
False
77 < 0 or 77 > 255 # 77 > 255 is true
True
False
但是,它似乎无法正常工作;在比较77
和255
时,似乎在第三个八位位组中出现了问题.
However, it doesn't seem to work properly; It looks like the problem occurred in the 3rd octet while comparing 77
with 255
.
我已经写了一些打印说明来说明问题区域.
I have put some print statements to illustrate the problem area.
推荐答案
您要比较的是字符串值(按词典顺序进行比较),而不是每个IP的int
值,请将它们与理解力:
You are comparing strings values (which compare lexicographically) and not the int
values for every IP, make them into ints with comprehensions:
min_ip = [int(i) for i in mask.split(' - ')[0].split('.')]
max_ip = [int(i) for i in mask.split(' - ')[1].split('.')]
ip = [int(i) for i in IP.split('.')]
最好不要对mask
中的每个IP进行两次拆分.先分手:
It's also best if you don't perform the split twice for every ip in mask
; split before hand:
s = mask.split(' - ')
min_ip, max_ip = [[int(i) for i in j.split('.')] for j in s]
如果将enumerate
与ip
一起使用,则可以说for
循环会更好:
Your for
loop could arguably be better if you used enumerate
with ip
:
for ind, val in enumerate(ip):
if val < min_ip[ind] or val > max_ip[ind]:
return False
这篇关于检查IP地址是否在给定范围内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!