问题
An attribute of ipaddress.IPv4Network
can be used to check if any IP address is reserved.
In 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')
I get:
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'
Why is this the case?
Note: In python 2, ip addresses must be passed to ipaddress
functions as unicode objects, hence calling unicode()
on the string input ip
.
回答1:
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.
来源:https://stackoverflow.com/questions/30996001/python-ipaddress-addressvalueerror-at-least-3-parts-expected