import socket
def is_valid_ip(ip):
try:
# 尝试将字符串解析为IP地址
socket.inet_aton(ip)
return True
except socket.error:
return False
# 测试
print(is_valid_ip("192.168.1.1")) # True
print(is_valid_ip("256.256.256.256")) # False
print(is_valid_ip("192.168.1")) # False