Python检测端口IP字符串是否合法的方法
发布时间:2020-07-18 13:51:56
来源:亿速云
阅读:98
作者:小猪
这篇文章主要讲解了Python检测端口IP字符串是否合法的方法,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。
IP合法性校验是开发中非常常用的,看起来很简单的判断,作用确很大,写起来比较容易出错,今天我们来总结一下,看一下3种常用的IP地址合法性校验的方法。
不使用正则表达式的方式:
def is_ip(ip: str) -> bool:
return True if [True] * 4 == [x.isdigit() and 0 <= int(x) <= 255 for x in ip.split(".")] else False
使用正则表达式的方式
import re
def isIP(str):
p = re.compile('^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$')
if p.match(str):
return True
else:
return False
另一种
def checkip(hostip):
pat = re.compile(r'([0-9]{1,3})\.')
r = re.findall(pat,hostip+".")
if len(r)==4 and len([x for x in r if int(x)>=0 and int(x)<=255])==4:
return True
else:
return False
看完上述内容,是不是对Python检测端口IP字符串是否合法的方法有进一步的了解,如果还想学习更多内容,欢迎关注亿速云行业资讯频道。