如何在 Python 中获取外部 IPv6 地址
你可以使用免费的 IPify 服务和 requests 来获取当前外部 IPv6 地址。注意这仅在运行脚本的主机上启用 IPv6 且具有有效 IPv6 配置时才有效。最值得注意的是,在 Docker 容器上通常只在 network_mode: host 中有效:
get_external_ipv6.py
#!/usr/bin/env python3
import requests
def get_current_ipv6():
"""获取当前外部 IPv6 地址,如果无法连接到 IPify 服务则返回 None"""
try:
return requests.get("https://api6.ipify.org", timeout=5).text
except requests.exceptions.ConnectionError as ex:
return None
# 使用示例
print(get_current_ipv6()) # 打印例如 2a01:4f9:c010:278::1Check out similar posts by category:
Networking, Python
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow