Modified get_client_ip function
This commit is contained in:
31
app.py
31
app.py
@@ -119,21 +119,48 @@ HTML_TEMPLATE = """<!doctype html>
|
||||
</html>
|
||||
"""
|
||||
|
||||
import ipaddress
|
||||
from flask import Flask, request, render_template_string
|
||||
# ...
|
||||
|
||||
def _is_private_ip(ip: str) -> bool:
|
||||
try:
|
||||
return ipaddress.ip_address(ip).is_private
|
||||
except ValueError:
|
||||
# se non è un IP valido, lo consideriamo "non utilizzabile"
|
||||
return True
|
||||
|
||||
|
||||
def get_client_ip():
|
||||
"""Determina l'IP reale del client dietro proxy / load balancer."""
|
||||
"""
|
||||
Prova a determinare l'IP pubblico del client:
|
||||
- prende la lista da X-Forwarded-For
|
||||
- sceglie il primo IP NON privato (non 10.x/192.168/172.16/127.x ecc.)
|
||||
- fallback su X-Real-IP
|
||||
- fallback su request.remote_addr
|
||||
"""
|
||||
# 1) X-Forwarded-For: "client, proxy1, proxy2..."
|
||||
xff = request.headers.get("X-Forwarded-For", "")
|
||||
if xff:
|
||||
parts = [p.strip() for p in xff.split(",") if p.strip()]
|
||||
# cerco il primo IP pubblico nella lista
|
||||
for ip in parts:
|
||||
if not _is_private_ip(ip):
|
||||
return ip
|
||||
# se proprio non trovo nulla di pubblico, prendo il primo
|
||||
if parts:
|
||||
return parts[0]
|
||||
|
||||
# 2) X-Real-IP
|
||||
xri = request.headers.get("X-Real-IP")
|
||||
if xri:
|
||||
if xri and not _is_private_ip(xri):
|
||||
return xri.strip()
|
||||
|
||||
# 3) Fallback: remote_addr così com'è
|
||||
return request.remote_addr or "Sconosciuto"
|
||||
|
||||
|
||||
|
||||
def fetch_ripe_info(ip: str):
|
||||
"""Recupera informazioni RIPEstat estese per l'IP."""
|
||||
info = {
|
||||
|
||||
Reference in New Issue
Block a user