Following the advice given here, I'm using the check the ipaddress
module to perform checks of type:
In [25]: IPv4Address(u'100.64.1.1') in IPv4Network(u'100.64.0.0/10')
Out[25]: True
Works fine in IPython. Yet when I turn it into a function:
import ipaddress
def isPrivateIp(ip):
ip4addressBlocks = [u'0.0.0.0/8', u'10.0.0.0/8', u'100.64.0.0/10', u'127.0.0.0/8', u'169.254.0.0/16', u'172.16.0.0/12', u'192.0.0.0/24', u'192.0.2.0/24', u'192.88.99.0/24',
u'192.168.0.0/16', u'198.18.0.0/15', u'198.51.100.0/24', u'203.0.113.0/24', u'224.0.0.0/4', u'240.0.0.0/4', u'255.255.255.255/32']
unicoded = unicode(ip)
if any(unicoded in ipaddress.IPv4Network(address) for address in ip4addressBlocks):
return True
else:
return False
print isPrivateIp(r'169.254.255.1')
I get:
File "isPrivateIP.py", line 14, in <module>
print isPrivateIp(r'169.254.255.1')
File "isPrivateIP.py", line 9, in isPrivateIp
if any(unicoded in ipaddress.IPv4Network(address) for address in ip4addressBlocks):
File "isPrivateIP.py", line 9, in <genexpr>
if any(unicoded in ipaddress.IPv4Network(address) for address in ip4addressBlocks):
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/ipaddress.py", line 705, in __contains__
if self._version != other._version:
AttributeError: 'str' object has no attribute '_version'
Why so?
You check if the unicode string
ip
is in the network, whereas before you've used anIPv4Address
instance.Your test must instead be