2015-06-23 90 views
0

ipaddress.IPv4Network的屬性可用於檢查是否保留了任何IP地址。Python:ipaddress.AddressValueError:至少需要3個部分

在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函數,因此在字符串輸入ip上調用unicode()

+3

您的代碼片段並不等同,您可以清楚地看到異常與「IPv6Address」類有關。 –

回答

1

ipaddress.IPv6Network()的預期輸入與ipaddress.IPv4Network()不同。如果您從代碼中刪除or ipaddress.IPv6Network(unicoded).is_private,它可以正常工作。你可以從here瞭解更多。

相關問題