Skip to content

Instantly share code, notes, and snippets.

@meisa233
Created October 21, 2025 06:29
Show Gist options
  • Select an option

  • Save meisa233/dcea0c81670594be68f0f1d495392330 to your computer and use it in GitHub Desktop.

Select an option

Save meisa233/dcea0c81670594be68f0f1d495392330 to your computer and use it in GitHub Desktop.
import socket
def get_local_ip():
"""返回本机用于对外通信的 IPv4 地址(不会发实际数据)"""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
# 这里用任意公网地址和端口(不必可达)
s.connect(("8.8.8.8", 80))
ip = s.getsockname()[0]
except Exception:
ip = "127.0.0.1"
finally:
s.close()
return ip
print(get_local_ip())
import requests
def get_public_ip(timeout=3):
urls = [
"https://api.ipify.org", # 简单返回 IP 文本
"https://ifconfig.me/ip",
"https://ident.me"
]
for u in urls:
try:
r = requests.get(u, timeout=timeout)
r.raise_for_status()
ip = r.text.strip()
if ip:
return ip
except Exception:
continue
return None
print(get_public_ip())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment