版权声明:如需转载,请注明转载地址。 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