网络编程
位置:首页>> 网络编程>> Python编程>> Python检测端口IP字符串是否合法

Python检测端口IP字符串是否合法

作者:hchan  发布时间:2023-09-03 11:51:26 

标签: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

来源:https://www.cnblogs.com/hchan/p/13031788.html

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com