python ipaddress_如何在Python中验证IP地址?

该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').

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值