天天看點

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