30 lines
796 B
Python
30 lines
796 B
Python
|
|
import requests
|
||
|
|
import logging
|
||
|
|
from typing import Optional
|
||
|
|
|
||
|
|
logger = logging.getLogger(__name__)
|
||
|
|
|
||
|
|
def get_public_ip() -> str:
|
||
|
|
"""
|
||
|
|
Detects public IP using external services.
|
||
|
|
Falls back to 127.0.0.1 on failure.
|
||
|
|
"""
|
||
|
|
services = [
|
||
|
|
"https://api.ipify.org",
|
||
|
|
"https://ifconfig.me/ip",
|
||
|
|
"https://icanhazip.com",
|
||
|
|
]
|
||
|
|
|
||
|
|
for service in services:
|
||
|
|
try:
|
||
|
|
response = requests.get(service, timeout=3)
|
||
|
|
if response.status_code == 200:
|
||
|
|
ip = response.text.strip()
|
||
|
|
# Basic validation could be added here
|
||
|
|
return ip
|
||
|
|
except requests.RequestException:
|
||
|
|
continue
|
||
|
|
|
||
|
|
logger.warning("Could not detect public IP, defaulting to 127.0.0.1")
|
||
|
|
return "127.0.0.1"
|