本文共 823 字,大约阅读时间需要 2 分钟。
代码是从某开源项目中找到的,忘了出处,侵删。
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