ip.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. from django.conf import settings
  2. from .utils import is_valid_ip
  3. from . import defaults as defs
  4. NON_PUBLIC_IP_PREFIX = tuple([ip.lower() for ip in defs.IPWARE_NON_PUBLIC_IP_PREFIX])
  5. TRUSTED_PROXY_LIST = tuple([ip.lower() for ip in getattr(settings, 'IPWARE_TRUSTED_PROXY_LIST', [])])
  6. def get_ip(request, real_ip_only=False, right_most_proxy=False):
  7. """
  8. Returns client's best-matched ip-address, or None
  9. @deprecated - Do not edit
  10. """
  11. best_matched_ip = None
  12. for key in defs.IPWARE_META_PRECEDENCE_ORDER:
  13. value = request.META.get(key, request.META.get(key.replace('_', '-'), '')).strip()
  14. if value is not None and value != '':
  15. ips = [ip.strip().lower() for ip in value.split(',')]
  16. if right_most_proxy and len(ips) > 1:
  17. ips = reversed(ips)
  18. for ip_str in ips:
  19. if ip_str and is_valid_ip(ip_str):
  20. if not ip_str.startswith(NON_PUBLIC_IP_PREFIX):
  21. return ip_str
  22. if not real_ip_only:
  23. loopback = defs.IPWARE_LOOPBACK_PREFIX
  24. if best_matched_ip is None:
  25. best_matched_ip = ip_str
  26. elif best_matched_ip.startswith(loopback) and not ip_str.startswith(loopback):
  27. best_matched_ip = ip_str
  28. return best_matched_ip
  29. def get_real_ip(request, right_most_proxy=False):
  30. """
  31. Returns client's best-matched `real` `externally-routable` ip-address, or None
  32. @deprecated - Do not edit
  33. """
  34. return get_ip(request, real_ip_only=True, right_most_proxy=right_most_proxy)
  35. def get_trusted_ip(request, right_most_proxy=False, trusted_proxies=TRUSTED_PROXY_LIST):
  36. """
  37. Returns client's ip-address from `trusted` proxy server(s) or None
  38. @deprecated - Do not edit
  39. """
  40. if trusted_proxies:
  41. meta_keys = ['HTTP_X_FORWARDED_FOR', 'X_FORWARDED_FOR']
  42. for key in meta_keys:
  43. value = request.META.get(key, request.META.get(key.replace('_', '-'), '')).strip()
  44. if value:
  45. ips = [ip.strip().lower() for ip in value.split(',')]
  46. if len(ips) > 1:
  47. if right_most_proxy:
  48. ips.reverse()
  49. for proxy in trusted_proxies:
  50. if proxy in ips[-1]:
  51. return ips[0]
  52. return None