Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get IP address of visitors using Flask for Python

People also ask

How do I find the IP address of a Flask visitor?

In this article, we learned three different methods to get the IP address of a user. We access the remote address directly with request. remote_addr , through the REMOTE_ADDR key from request. environ , and in the cases where the user is using a proxy we should check the HTTP_X_FORWARDED_FOR key of request.

How do I find the IP address of a Flask in Python?

To get IP address of visitors using Flask for Python, we can use the request. remote_addr property. to get the current client's IP address with request. remote_addr .


See the documentation on how to access the Request object and then get from this same Request object, the attribute remote_addr.

Code example

from flask import request
from flask import jsonify

@app.route("/get_my_ip", methods=["GET"])
def get_my_ip():
    return jsonify({'ip': request.remote_addr}), 200

For more information see the Werkzeug documentation.


Proxies can make this a little tricky, make sure to check out ProxyFix (Flask docs) if you are using one. Take a look at request.environ in your particular environment. With nginx I will sometimes do something like this:

from flask import request   
request.environ.get('HTTP_X_REAL_IP', request.remote_addr)   

When proxies, such as nginx, forward addresses, they typically include the original IP somewhere in the request headers.

Update See the flask-security implementation. Again, review the documentation about ProxyFix before implementing. Your solution may vary based on your particular environment.


Actually, what you will find is that when simply getting the following will get you the server's address:

request.remote_addr

If you want the clients IP address, then use the following:

request.environ['REMOTE_ADDR']

The user's IP address can be retrieved using the following snippet:

from flask import request
print(request.remote_addr)