Skip to content

Commit f19a344

Browse files
author
Inbal Tako
committed
Normalize ip extraction
1 parent 86cf57b commit f19a344

File tree

1 file changed

+5
-11
lines changed

1 file changed

+5
-11
lines changed

securenative/utils/request_utils.py

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -40,23 +40,17 @@ def get_client_ip_from_request(request, options):
4040
continue
4141

4242
try:
43-
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
44-
if x_forwarded_for:
45-
ip = x_forwarded_for.split(',')[0].strip()
46-
else:
47-
ip = request.META.get('REMOTE_ADDR')
48-
49-
if ip is None or ip == "":
50-
ip = request.environ.get('HTTP_X_FORWARDED_FOR', request.environ.get('REMOTE_ADDR', "")).split(',')[0].strip()
51-
52-
return ip
43+
for header in RequestUtils.IP_HEADERS:
44+
ips = request.META.get[header].split(',')
45+
return RequestUtils.get_valid_ip(ips)
5346
except Exception:
5447
return ""
5548

5649
@staticmethod
5750
def get_remote_ip_from_request(request):
5851
try:
59-
return request.raw._original_response.fp.raw._sock.getpeername()[0]
52+
if len(request.raw._original_response.fp.raw._sock.getpeername()) > 0:
53+
return request.raw._original_response.fp.raw._sock.getpeername()[0]
6054
except Exception:
6155
return ""
6256

0 commit comments

Comments
 (0)