如何在 Python 中获取外部 IPv4 地址
你可以使用免费的 IPify 服务和 requests 来获取当前 IPv4 地址:
how-to-get-external-ipv4-address-in-python.py
#!/usr/bin/env python3
import requests
def get_current_ipv4():
"""获取当前外部 IPv4 地址,如果无法连接到 IPify 服务则返回 None"""
try:
return requests.get("https://api4.ipify.org", timeout=5).text
except requests.exceptions.ConnectionError as ex:
return None
# 使用示例
print(get_current_ipv4()) # 打印例如 95.216.138.188Check 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