Files

30 lines
694 B
Python

"""客户端 IP / 局域网判断。"""
from __future__ import annotations
import ipaddress
from fastapi import Request
def client_ip(request: Request) -> str:
xff = request.headers.get("x-forwarded-for") or ""
if xff.strip():
return xff.split(",")[0].strip()
if request.client and request.client.host:
return request.client.host
return ""
def is_lan_ip(ip: str) -> bool:
raw = (ip or "").strip()
if not raw:
return False
if raw in ("localhost", "::1"):
return True
try:
addr = ipaddress.ip_address(raw.split("%")[0])
except ValueError:
return False
return bool(addr.is_loopback or addr.is_private)