fixes client ip detection for v6

This commit is contained in:
Abhimanyu Saharan 2023-12-07 05:24:40 +05:30
parent fe3f21105c
commit 988e86c45b

View File

@ -1,4 +1,4 @@
from netaddr import IPAddress
from netaddr import AddrFormatError, IPAddress
__all__ = (
'get_client_ip',
@ -17,10 +17,15 @@ def get_client_ip(request, additional_headers=()):
)
for header in HTTP_HEADERS:
if header in request.META:
client_ip = request.META[header].split(',')[0].partition(':')[0]
ip = request.META[header].split(',')[0].strip()
# Check if the IP address is v6 or v4
if ip.count(':') > 1:
client_ip = ip
else:
client_ip = ip.partition(':')[0]
try:
return IPAddress(client_ip)
except ValueError:
except (AddrFormatError, ValueError):
raise ValueError(f"Invalid IP address set for {header}: {client_ip}")
# Could not determine the client IP address from request headers