[英]Check if user's IP address is in a range of IP's
在我的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解決方案都可以。
我們的想法是拆分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
不確定這是最優的,但這是基礎python,不需要額外的包。
ip_range
,創建一個列表,如果是簡單值,則包含1個元素,如果是range
則創建范圍。 因此它創建了一個包含4個int / range對象的列表。 split
版本zip
它,並測試另一個的范圍內的每個值 注意:使用range
,確保超高速in
測試(在Python 3)( 為什么是“位於范圍千兆(千萬億○一)”在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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.