问题描述
ipaddress.IPv4Network
属性可用于检查是否保留了任何IP地址.
An attribute of ipaddress.IPv4Network
can be used to check if any IP address is reserved.
在IPython中:
In [52]: IPv4Address(u'169.254.255.1').is_private
Out[52]: False
但是,如果我在函数中尝试完全相同的事情:
Yet if I try the exact same thing in a function:
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
函数,因此在字符串输入ip
上调用unicode()
.
Note: In python 2, ip addresses must be passed to ipaddress
functions as unicode objects, hence calling unicode()
on the string input ip
.
推荐答案
ipaddress.IPv6Network()
的预期输入与ipaddress.IPv4Network()
不同.如果您从代码中删除or ipaddress.IPv6Network(unicoded).is_private
,则可以正常工作.您可以从此处阅读更多信息.
The expected input for ipaddress.IPv6Network()
is different than ipaddress.IPv4Network()
. If you remove or ipaddress.IPv6Network(unicoded).is_private
from your code it works fine. You can read more from here.
这篇关于Python:ipaddress.AddressValueError:至少应包含3个部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!