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
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。