Skip to content

Commit

Permalink
Add request.client_ip
Browse files Browse the repository at this point in the history
  • Loading branch information
Tronic committed Jul 13, 2023
1 parent dc3c4d1 commit ffffc7c
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 6 deletions.
24 changes: 18 additions & 6 deletions sanic/request/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -838,19 +838,31 @@ def forwarded(self) -> Options:
@property
def remote_addr(self) -> str:
"""
Client IP address, if available.
1. proxied remote address `self.forwarded['for']`
2. local remote address `self.ip`
Client IP address, if available from proxy.
:return: IPv4, bracketed IPv6, UNIX socket name or arbitrary string
:rtype: str
"""
if not hasattr(self, "_remote_addr"):
self._remote_addr = str(
self.forwarded.get("for", "")
) # or self.ip
self._remote_addr = str(self.forwarded.get("for", ""))
return self._remote_addr

@property
def client_ip(self) -> str:
"""
Client IP address.
1. proxied remote address `self.forwarded['for']`
2. local peer address `self.ip`
New in Sanic 23.6. Prefer this over `remote_addr` for determining the
client address regardless of whether the service runs behind a proxy
or not (proxy deployment needs separate configuration).
:return: IPv4, bracketed IPv6, UNIX socket name or arbitrary string
:rtype: str
"""
return self.remote_addr or self.ip

@property
def scheme(self) -> str:
"""
Expand Down
2 changes: 2 additions & 0 deletions tests/test_requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -513,6 +513,7 @@ async def handler(request):
request, response = app.test_client.get("/", headers=headers)
assert response.json == {"for": "127.0.0.2", "proto": "ws"}
assert request.remote_addr == "127.0.0.2"
assert request.client_ip == "127.0.0.2"
assert request.scheme == "ws"
assert request.server_name == "local.site"
assert request.server_port == 80
Expand Down Expand Up @@ -737,6 +738,7 @@ async def handler(request):
headers = {"X-Forwarded-For": "127.0.1.1"}
request, response = app.test_client.get("/", headers=headers)
assert request.remote_addr == ""
assert request.client_ip == "127.0.0.1"
assert response.body == b""

headers = {"X-Forwarded-For": "127.0.0.1, 127.0.1.2"}
Expand Down

0 comments on commit ffffc7c

Please sign in to comment.