Get IP address of visitors using Flask for Python

245,750

Solution 1

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.

Solution 2

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.

Solution 3

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

Solution 4

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

Solution 5

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

from flask import request
print(request.remote_addr)
Share:
245,750

Related videos on Youtube

Jon Cox
Author by

Jon Cox

Check out my UK train times iPhone app: Railboard https://itunes.apple.com/us/app/railboard/id1278747705?ls=1&mt=8

Updated on February 24, 2022

Comments

  • Jon Cox
    Jon Cox about 2 years

    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?

  • Jonathan Simon Prates
    Jonathan Simon Prates over 10 years
    Some times, it can be useful: request.access_route[0]
  • Ry-
    Ry- almost 10 years
    Only if you’re behind a reverse proxy, no?
  • jpmc26
    jpmc26 almost 10 years
    @minitech I would say that your code should not care whether you're behind a proxy or not. If this option works reliably irrespective of the reverse proxy and the other assumes you're not behind a reverse proxy, then this should be preferred. (I'd test this if I could easily set up a reverse proxy, but that would take more time than I have at the moment.)
  • Ry-
    Ry- almost 10 years
    @jpmc26: I see no reason why it should work at all. request.remote_addr sounds like a property that should get a remote address depending on whether the reverse proxy is trusted.
  • Chiedo
    Chiedo almost 10 years
    Using mod_wsgi, request.remote_addr returned the servers address every time. request.environ['REMOTE_ADDR'] got me the client's public IP address. Maybe I'm missing something?
  • Rasty Turek
    Rasty Turek over 9 years
    As for nginx, it sends the real IP address under HTTP_X_FORWARDED_FOR so make sure you don't end up with localhost for each request.
  • drahnr
    drahnr about 9 years
    This works when you set the appropriate fields in the config of your reverse proxy. Used in production.
  • pors
    pors over 8 years
    @drahnr yes indeed. The above code works if in e.g. nginx you set: proxy_set_header X-Real-IP $remote_addr;
  • lostdorje
    lostdorje over 8 years
    @pors - it works. i have the same settings in my nginx conf as you. but i still don't understand why the code: request.headers.get('X-Real-IP', request.remote_addr) doesn't work. Note, intuitively I'd get the value from headers and use the name 'X-Real-IP' as that's how my nginx conf is.
  • datashaman
    datashaman over 6 years
    This is not true if the app is running behind a proxy server like nginx. Which it often is in production.
  • Romano Vacca
    Romano Vacca almost 6 years
    This answer together with changing my nginx config according to this blog worked for me. calvin.me/forward-ip-addresses-when-using-nginx-proxy
  • Uri Goren
    Uri Goren almost 6 years
    Returns 127.0.0.1 due to proxy, not very helpful.
  • Mark Amery
    Mark Amery over 5 years
    @jpmc26 You frequently do need to care if you're behind a remote proxy. If you are, then the IP than connects to you will be of the remote proxy server, and you'll need to rely on the headers it adds to get the original client IP. If you're not, those headers typically won't be present, and you'll want to use the connection IP as the client IP. And you can't necessarily just check for the header and fall back to the connection IP if it's not present, because then if you're not behind a reverse proxy a client can spoof their IP, which in many circumstances will be a security issue.
  • jpmc26
    jpmc26 over 5 years
    @MarkAmery I mean that the framework should handle those details for you. Application code ("your" code) should not care. The proxy itself should control the headers and make them work in a way that spoofing is ineffective.
  • Mark Amery
    Mark Amery over 5 years
    @jpmc26 A framework could in principle handle this for you, but only if you explicitly told it, in its config, whether it was behind a reverse proxy. Also, as far as I know, no frameworks do in fact handle this, so the reality is that application code does have to care, even if we can imagine a hypothetical world where this stuff gets handled by frameworks. The reverse proxy can't possibly take responsibility for handling this, because there's no way for it to communicate an IP to a server behind it that can't be spoofed by a client talking to a server that isn't behind a proxy.
  • Arel
    Arel almost 4 years
    Note: this is insecure if not served behind a proxy. Check out ProxyFix instead.
  • English Rain
    English Rain over 2 years
    Thanks, this was the only answer that worked for me.
  • egvo
    egvo over 2 years
    I have mixed @pegasus and yours answers, works well!