Home » Python » Get IP address of visitors

Get IP address of visitors

Posted by: admin November 1, 2017 Leave a comment

Questions:

I’m making a website where users can log on and download files, using the Flask micro-framework (based on Werkzeug) which uses Python (2.6 in my case).

I need to get the IP address of users when they log on (for logging purposes).
Does anyone know how to do this? Surely there is a way to do it with Python?

Answers:

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.

Questions:
Answers:

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']

Questions:
Answers:

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.

Questions:
Answers:

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

from flask import request
print request.remote_addr

Questions:
Answers:

httpbin.org uses this method:

return jsonify(origin=request.headers.get('X-Forwarded-For', request.remote_addr))