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