ipaddress.IPv4Network
的属性可用于检查是否保留了任何IP地址。
在IPython中:
In [52]: IPv4Address(u'169.254.255.1').is_private
Out[52]: False
然而,如果我在函数中尝试完全相同的东西:
import ipaddress
def isPrivateIp(ip):
unicoded = unicode(ip)
if ipaddress.IPv4Network(unicoded).is_private or ipaddress.IPv6Network(unicoded).is_private:
return True
else:
return False
print isPrivateIp(r'169.254.255.1')
我明白了:
File "isPrivateIP.py", line 13, in <module>
print isPrivateIp(ur'169.254.255.1')
File "isPrivateIP.py", line 7, in isPrivateIp
if ipaddress.IPv4Network(unicoded).is_private or ipaddress.IPv6Network(unicoded).is_private:
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/ipaddress.py", line 2119, in __init__
self.network_address = IPv6Address(self._ip_int_from_string(addr[0]))
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/ipaddress.py", line 1584, in _ip_int_from_string
raise AddressValueError(msg)
ipaddress.AddressValueError: At least 3 parts expected in u'169.254.255.1'
为什么会这样?
注意:在python 2中,必须将ip地址作为unicode对象传递给ipaddress
函数,因此在字符串输入unicode()
上调用ip
。
答案 0 :(得分:1)
ipaddress.IPv6Network()
的预期输入与ipaddress.IPv4Network()
不同。如果您从代码中删除or ipaddress.IPv6Network(unicoded).is_private
,则可以正常使用。您可以从here了解更多信息。