1 判断ip是否有效
方法一
import socket
def is_valid_ip(ip):
"""Returns true if the given string is a well-formed IP address.
Supports IPv4 and IPv6.
"""
ip = ip.strip()
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
方法二
import ipaddress
import sys
def valid_ip(ip):
try:
#判断 python 版本
if sys.version_info[0] == 2:
ipaddress.ip_address(ip.strip().decode("utf-8"))
elif sys.version_info[0] == 3:
ipaddress.ip_address(bytes(ip.strip().encode("utf-8")))
return True
except Exception as e:
return False
2 判断ip 是否是内网
import ipaddress
import sys
def private_ip(ip):
try:
#判断 python 版本
if sys.version_info[0] == 2:
return ipaddress.ip_address(ip.strip().decode("utf-8")).is_private
elif sys.version_info[0] == 3:
return ipaddress.ip_address(bytes(ip.strip().encode("utf-8"))).is_private
except Exception as e:
return False