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

(编辑:jimmy 日期: 2025/5/4 浏览:2)

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]"htmlcode">
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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

一句话新闻

Windows上运行安卓你用过了吗
在去年的5月23日,借助Intel Bridge Technology以及Intel Celadon两项技术的驱动,Intel为PC用户带来了Android On Windows(AOW)平台,并携手国内软件公司腾讯共同推出了腾讯应用宝电脑版,将Windows与安卓两大生态进行了融合,PC的使用体验随即被带入到了一个全新的阶段。