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

13次阅读

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

海淀小霸王

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

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

xuecan

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

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

felix021

def is_valid_ip(ip):  
    """Returns true if the given string is a well-formed IP address. 
 
    Supports IPv4 and IPv6. 
    """  
    if not ip or '\x00' in ip:  
        # getaddrinfo resolves empty strings to localhost, and truncates  
        # on zero bytes.  
        return False  
    try:  
        res = socket.getaddrinfo(ip, 0, socket.AF_UNSPEC,  
                                 socket.SOCK_STREAM,  
                                 0, socket.AI_NUMERICHOST)  
        return bool(res)  
    except socket.gaierror as e:  
        if e.args[0] == socket.EAI_NONAME:  
            return False  
        raise  
    return True 

yangh1368

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

StormX

正文完