Skip to content

Instantly share code, notes, and snippets.

@deangrant
Last active January 5, 2023 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deangrant/09f6d069af1fe848e7ece2b57a6aac8d to your computer and use it in GitHub Desktop.
Save deangrant/09f6d069af1fe848e7ece2b57a6aac8d to your computer and use it in GitHub Desktop.
Returns client IP address of a user in Flask
def get_client_ip(
request: list
) -> str:
"""
Returns the client's IP address from an HTTP request object.
Parameters:
request (list): A list representing the HTTP request object.
Returns:
str: The client's IP address.
"""
# Try to get the client's IP address from the HTTP_X_FORWARDED_FOR field
# in the request's environment. This field is set by a reverse proxy or
# load balancer to the client's IP address, and can contain a list of
# IP addresses separated by commas if the request passed through multiple
# proxies.
try:
# Return the first IP address in the list.
return request.environ["HTTP_X_FORWARDED_FOR"].split(
","
)[0].strip()
except(
KeyError,
IndexError
):
# If the HTTP_X_FORWARDED_FOR field is not present in the environment
# or if an IndexError is raised when trying to access the first IP
# address in the list, fall back to the remote_addr field of the
# request object.
pass
return request.remote_addr
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment