首页 > Python验证用户输入IP的合法性,有什么好方法吗?

Python验证用户输入IP的合法性,有什么好方法吗?

如题,<input type="text" name="ip" id="ip" /> 在text里表单输入的字符串


felix021的方法更好,相对于iCode的执行效率更高


def ip_check(ip):
    q = ip.split('.')
    return len(q) == 4 and len(filter(lambda x: x >= 0 and x <= 255, \
        map(int, filter(lambda x: x.isdigit(), q)))) == 4

import re
ip_str = "12.34.56.78"
 
def ipFormatChk(ip_str):
   pattern = r"\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"
   if re.match(pattern, ip_str):
      return True
   else:
      return False

print ipFormatChk(ip_str)

@iCode 的方法对 IPv4 的地址是有效的。不过 IPv6 的情况要复杂许多。所以比较好的办法是使用专门处理 IP 地址的库来检查有效性。

从 Python 3.3 开始标准库中提供了 ipaddress 模块,之前的 Python 版本则可以通过 PyPi 安装相应的版本。

【热门文章】
【热门文章】