Checking if IP address lies within a given range

送分小仙女□ 提交于 2019-12-06 05:48:42
Jim Fasarakis Hilliard

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('.')]

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]

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

When you call the match function strings are passed in which are split according to the octets. However, when the comparisons are made the octet being compared is still a string. Thus '7' > '2' for the third octet. If you convert each octet to an integer as:

if int(ip[i]) < int(min_ip[i]) or int(ip[i]) > int(max_ip[i]):

You will get the expected response.

What is wrong in your script is - You are comparing string & not numbers.

You can try this:

def match(mask, IP):
    min_ip = mask.split(' - ')[0].split('.')
    print min_ip
    max_ip = mask.split(' - ')[1].split('.')
    print max_ip
    ip = IP.split('.')
    print ip
    for i in range(4):
        if int(ip[i]) < int(min_ip[i]) or int(ip[i]) > int(max_ip[i]):
            return False
    return True
print(match("180.179.0.0 - 180.179.255.255", "180.179.77.11"))

Without loop, hope its useful.

def match(mask, IP):
    min_ip = mask.split(' - ')[0].split('.')
    max_ip = mask.split(' - ')[1].split('.')
    range4 = range(int(min_ip[-2]), int(max_ip[-2]) + 1)
    range3 = range(int(min_ip[-1]), int(max_ip[-1]) + 1)

    ip = IP.split(".")
    if ( (int(ip[-2]) in range3) and (int(ip[-1]) in range4) ):
        return True

    return False

print match("180.179.0.0 - 180.179.255.255", "180.179.77.11")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!