request.py 725 B

123456789101112131415161718192021222324252627
  1. from netaddr import IPAddress
  2. __all__ = (
  3. 'get_client_ip',
  4. )
  5. def get_client_ip(request, additional_headers=()):
  6. """
  7. Return the client (source) IP address of the given request.
  8. """
  9. HTTP_HEADERS = (
  10. 'HTTP_X_REAL_IP',
  11. 'HTTP_X_FORWARDED_FOR',
  12. 'REMOTE_ADDR',
  13. *additional_headers
  14. )
  15. for header in HTTP_HEADERS:
  16. if header in request.META:
  17. client_ip = request.META[header].split(',')[0]
  18. try:
  19. return IPAddress(client_ip)
  20. except ValueError:
  21. raise ValueError(f"Invalid IP address set for {header}: {client_ip}")
  22. # Could not determine the client IP address from request headers
  23. return None