使用IPtools python包我试图查看ip地址是否在特定范围内。这是我的代码:
for line in g:
org= line.split("|")[0]
ranges = ast.literal_eval(line.split('|')[1])
for range in ranges:
start,end = range
range_s = IpRange(start,end)
if '198.0.184.126' in range_s is True:
print (range_s)
以下是我的文件的样子:
FOP Michail Mandryk |[('91.195.172.0', '91.195.173.255'), ('195.95.222.0', '195.95.223.255')]
Circle 3 Inc.|[('66.64.129.28', '66.64.129.31'), ('216.23.64.120', '216.23.64.120'), ('216.215.250.46', '216.215.250.47')]
a1web.com.br|[('50.116.92.89', '50.116.92.89')]
Shandong Dezhou decheng district government|[('61.133.124.64', '61.133.124.79')]
Global ICT Solutions (ShangHai) CO.,LTD|[('43.247.100.0', '43.247.103.255')]
VendorCert|[('173.1.96.112', '173.1.96.127')]
Lowell City Library|[('198.0.184.112', '198.0.184.127')]
abc|[('123.0.0.0/8' , '12.12.3.0/8')]
我收到此错误,我找不到原因。有人可以帮忙吗?
TypeError Traceback (most recent call last)
<ipython-input-59-420def563a4e> in <module>()
19
20 # print (start,end)
---> 21 range_s = IpRange(start,end)
22 # if '198.0.184.126' in range_s is True:
23 print (range_s)
/opt/miniconda3/lib/python3.4/site-packages/iptools/__init__.py in __init__(self, start, end)
158 start = _address2long(start)
159 end = _address2long(end)
--> 160 self.startIp = min(start, end)
161 self.endIp = max(start, end)
162 self._len = self.endIp - self.startIp + 1
TypeError: unorderable types: NoneType() < NoneType()
答案 0 :(得分:3)
iptools._address2long()
function如果无法解析有效的IPv4或IPv6地址,则返回None
。
您的start
和end
地址都无法解析,并且min()
两个None
值上的>>> min(None, None)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unorderable types: NoneType() < NoneType()
函数失败,但您获得的异常:
try:
range_s = IpRange(start,end)
except TypeError:
print('Problematic addresses:', start, end)
raise
三次检查您传入的地址以确保它们有效。您可以捕获此异常以打印导致问题的值,例如:
is True
在旁注中,不需要在if
语句中测试if
。这就是的if '198.0.184.126' in range_s:
print (range_s)
。通过比较链接,声明并不意味着您认为它在任何情况下都意味着什么。严格使用:
is True
使用('198.0.184.126' in range_s) and (range_s is True)
时,您确实在测试{{1}},永远不会为真。