Python检测端口IP字符串是否合法
IP合法性校验是开发中非常常用的,看起来很简单的判断,作用确很大,写起来比较容易出错,今天我们来总结一下,看一下3种常用的IP地址合法性校验的方法。
不使用正则表达式的方式:
defis_ip(ip:str)->bool:
returnTrueif[True]*4==[x.isdigit()and0<=int(x)<=255forxinip.split(".")]elseFalse
使用正则表达式的方式
importre
defisIP(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?)$')
ifp.match(str):
returnTrue
else:
returnFalse
另一种
defcheckip(hostip):
pat=re.compile(r'([0-9]{1,3})\.')
r=re.findall(pat,hostip+".")
iflen(r)==4andlen([xforxinrifint(x)>=0andint(x)<=255])==4:
returnTrue
else:
returnFalse
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短