喵喵时光机
该IPY模块(专为处理IP地址的模块)将抛出无效地址的ValueError异常。>>> from IPy import IP>>> IP('127.0.0.1')IP('127.0.0.1')>>> IP('277.0.0.1')Traceback (most recent call last):
...ValueError: &#39;277.0.0.1&#39;: single byte must be 0 <&#61; byte >> IP(&#39;foobar&#39;)Traceback (most recent call last):
...ValueError: invalid literal for long() with base 10: &#39;foobar&#39;然而&#xff0c;就像Dustin的回答一样&#xff0c;它会接受“4”和“192.168”之类的东西&#xff0c;因为如上所述&#xff0c;这些是IP地址的有效表示。如果您使用的是Python 3.3或更高版本&#xff0c;它现在包含ipaddress模块&#xff1a;>>> import ipaddress>>> ipaddress.ip_address(&#39;127.0.0.1&#39;)IPv4Address(&#39;127.0.0.1&#39;)>>> ipaddress.ip_address(&#39;277.0.0.1&#39;)Traceback (most recent call last):
File "", line 1, in
File "/usr/lib/python3.3/ipaddress.py", line 54, in ip_address
address)ValueError: &#39;277.0.0.1&#39; does not appear to be an IPv4 or IPv6 address>>> ipaddress.ip_address(&#39;foobar&#39;)Traceback (most recent call last):
File "", line 1, in
File "/usr/lib/python3.3/ipaddress.py", line 54, in ip_address
address)ValueError: &#39;foobar&#39; does not appear to be an IPv4 or IPv6 address对于Python 2&#xff0c;如果安装python-ipaddress&#xff0c;则可以使用ipaddress获得相同的功能&#xff1a;pip install ipaddress该模块与Python 2兼容&#xff0c;并提供了与Python 3.3之后的Python标准库中包含的ipaddress模块非常相似的API。更多细节在这里。在Python 2中&#xff0c;您需要将IP地址字符串显式转换为unicode : ipaddress.ip_address(u&#39;127.0.0.1&#39;).