Python基础系列-判断字段是否IP

版权声明:如需转载,请注明转载地址。 https://blog.csdn.net/oJohnny123/article/details/82116511

代码是从某开源项目中找到的,忘了出处,侵删。

 

def is_ip(value):
    import sys, os, socket
    PY2 = sys.version_info[0] == 2
    
    """Determine if the given string is an IP address.

    Python 2 on Windows doesn't provide ``inet_pton``, so this only
    checks IPv4 addresses in that environment.

    :param value: value to check
    :type value: str

    :return: True if string is an IP address
    :rtype: bool
    """
    if PY2 and os.name == 'nt':
        try:
            socket.inet_aton(value)
            return True
        except socket.error:
            return False

    for family in (socket.AF_INET, socket.AF_INET6):
        try:
            socket.inet_pton(family, value)
        except socket.error:
            pass
        else:
            return True

    return False

 

上一篇:javascript中未初始化的变量和未定义的变量的区别


下一篇:使用Python-Flask框架开发Web网站系列课程(一)构建项目