1. 检查ip的有效性:
示例代码:
import ipaddress
# 检查ip的有效性
def check_valid_ip(ip):
try:
ipaddress.ip_address(ip.strip())
return True
except Exception as e:
print(e)
return False
if __name__ == '__main__':
ips = ['192.168.1.1', '192.168.1.366', '10.25.1.36']
for ip in ips:
res = check_valid_ip(ip)
if res:
print(ip, res)
else:
print(ip, res)
运行结果:
2.判断IP是内网还是外网
示例代码:
import ipaddress
# 判断ip是内网还是外网
def check_ip_is_internet(ip):
try:
return ipaddress.ip_address(ip.strip()).is_private
except Exception as e:
print(e)
return False
if __name__ == '__main__':
ips = ['192.168.1.1', '192.168.1.366', '10.25.1.36']
for ip in ips:
res = check_ip_is_internet(ip)
if res:
print(ip, res)
else:
print(ip, res)
运行结果:
更多ipaddress库用法详解博文:
python中ipaddress库用法详解_IT之一小佬的博客-CSDN博客_ipaddress python
参考博文:
python3 判断ip有效性 是否是内网ip_whatday的博客-CSDN博客_python 判断内网ip