-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
64 lines (50 loc) · 1.75 KB
/
Copy pathserver.py
File metadata and controls
64 lines (50 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# server.py
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from starlette.middleware.cors import CORSMiddleware
import re
app = FastAPI(title="IP Detector")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # aceita todas as origens
allow_credentials=False, # NÃO use True com allow_origins=["*"] (navegador bloqueará)
allow_methods=["*"], # GET, POST, PUT, DELETE...
allow_headers=["*"], # todos os headers
)
def extract_ip_from_forwarded(forwarded: str) -> str | None:
# Forwarded: for=1.2.3.4;proto=http;by=...
m = re.search(r'for=([^;,\s]+)', forwarded)
if m:
return m.group(1).strip('"')
return None
def get_client_ip(request: Request) -> str:
headers = request.headers
# 1) X-Forwarded-For (padrão: client, proxy1, proxy2)
xff = headers.get("x-forwarded-for")
if xff:
return xff.split(",")[0].strip()
# 2) Outras headers comuns
for h in ("x-real-ip", "cf-connecting-ip", "true-client-ip"):
val = headers.get(h)
if val:
return val.split(",")[0].strip()
# 3) Forwarded (RFC 7239)
forwarded = headers.get("forwarded")
if forwarded:
ip = extract_ip_from_forwarded(forwarded)
if ip:
return ip
# 4) Fallback para host informado pelo framework (endereço remoto da conexão)
client = request.client
if client:
return client.host
return "unknown"
@app.get("/ip")
async def ip(request: Request):
client_ip = get_client_ip(request)
return JSONResponse({"ip": client_ip})
if __name__ == "__main__":
import os
import uvicorn
port = int(os.environ.get("PORT", 8000))
uvicorn.run("server:app", host="0.0.0.0", port=port)