Get IP address of visitors using Flask for Python
--
Track title: CC D Schuberts Piano Sonata D 850 in D
--
Chapters
00:00 Question
00:36 Accepted answer (Score 413)
01:04 Answer 2 (Score 129)
01:56 Answer 3 (Score 92)
02:17 Answer 4 (Score 45)
02:38 Thank you
--
Full question
https://stackoverflow.com/questions/3759...
Question links:
[Flask micro-framework]: http://flask.pocoo.org/
[Werkzeug]: http://werkzeug.pocoo.org/
Accepted answer links:
[how to access the Request object]: http://flask.pocoo.org/docs/quickstart/#...
[Werkzeug documentation]: http://werkzeug.pocoo.org/docs/wrappers/...
Answer 2 links:
[ProxyFix]: http://werkzeug.pocoo.org/docs/0.14/cont...
[Flask docs]: http://flask.pocoo.org/docs/1.0/deployin...
[See the flask-security implementation]: https://github.com/mattupstate/flask-sec...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #flask #ipaddress #werkzeug
#avk47
ACCEPTED ANSWER
Score 441
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.
ANSWER 2
Score 137
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.
ANSWER 3
Score 97
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']
ANSWER 4
Score 61
The below code always gives the public IP of the client (and not a private IP behind a proxy).
from flask import request
if request.environ.get('HTTP_X_FORWARDED_FOR') is None:
print(request.environ['REMOTE_ADDR'])
else:
print(request.environ['HTTP_X_FORWARDED_FOR']) # if behind a proxy