Last active
January 5, 2023 14:03
-
-
Save deangrant/09f6d069af1fe848e7ece2b57a6aac8d to your computer and use it in GitHub Desktop.
Returns client IP address of a user in Flask
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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