Get IP address of visitors using Flask for Python

PythonFlaskIp AddressWerkzeug

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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 - Python

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 - Python

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 - Python

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 - Python

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

from flask import request
print(request.remote_addr)

Solution 6 - Python

I have Nginx and With below Nginx Config:

server {
    listen 80;
    server_name xxxxxx;
    location / {
               proxy_set_header   Host                 $host;
               proxy_set_header   X-Real-IP            $remote_addr;
               proxy_set_header   X-Forwarded-For      $proxy_add_x_forwarded_for;
               proxy_set_header   X-Forwarded-Proto    $scheme;

               proxy_pass http://x.x.x.x:8000;
        }
}

@tirtha-r solution worked for me

#!flask/bin/python
from flask import Flask, jsonify, request
app = Flask(__name__)

@app.route('/', methods=['GET'])
def get_tasks():
    if request.environ.get('HTTP_X_FORWARDED_FOR') is None:
        return jsonify({'ip': request.environ['REMOTE_ADDR']}), 200
    else:
        return jsonify({'ip': request.environ['HTTP_X_FORWARDED_FOR']}), 200

if __name__ == '__main__':
    app.run(debug=True,host='0.0.0.0', port=8000)

My Request and Response:

curl -X GET http://test.api

{
    "ip": "Client Ip......"
}

Solution 7 - Python

httpbin.org uses this method:

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

Solution 8 - Python

If you use Nginx behind other balancer, for instance AWS Application Balancer, HTTP_X_FORWARDED_FOR returns list of addresses. It can be fixed like that:

if 'X-Forwarded-For' in request.headers:
    proxy_data = request.headers['X-Forwarded-For']
    ip_list = proxy_data.split(',')
    user_ip = ip_list[0]  # first address in list is User IP
else:
    user_ip = request.remote_addr  # For local development

Solution 9 - Python

If You are using Gunicorn and Nginx environment then the following code template works for you.

addr_ip4 = request.remote_addr

Solution 10 - Python

This should do the job. It provides the client IP address (remote host).

Note that this code is running on the server side.

from mod_python import apache

req.get_remote_host(apache.REMOTE_NOLOOKUP)

Solution 11 - Python

I did not get any of the above work with Google Cloud App Engine. This worked, however

ip = request.headers['X-Appengine-User-Ip']

The proposed request.remote_addr did only return local host ip every time.

Solution 12 - Python

Here is the simplest solution, and how to use in production.

from flask import Flask, request
from werkzeug.middleware.proxy_fix import ProxyFix
app = Flask(__name__)
# Set environment from any X-Forwarded-For headers if proxy is configured properly
app.wsgi_app = ProxyFix(app.wsgi_app, x_host=1)

@app.before_request
def before_process():
   ip_address = request.remote_addr

Add include proxy_params to /etc/nginx/sites-available/$project. proxy_params forwards headers to be parsed by ProxyFix

  location / {
    proxy_pass http://unix:$project_dir/gunicorn.sock;
    include proxy_params;
  }

sudo cat /etc/nginx/proxy_params

proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJon CoxView Question on Stackoverflow
Solution 1 - PythonTarantulaView Answer on Stackoverflow
Solution 2 - PythonStephen FuhryView Answer on Stackoverflow
Solution 3 - PythonChiedoView Answer on Stackoverflow
Solution 4 - PythonTirtha RView Answer on Stackoverflow
Solution 5 - PythondavidgView Answer on Stackoverflow
Solution 6 - PythonSoliView Answer on Stackoverflow
Solution 7 - PythonPegasusView Answer on Stackoverflow
Solution 8 - PythonVladView Answer on Stackoverflow
Solution 9 - PythonJyotiprakash panigrahiView Answer on Stackoverflow
Solution 10 - PythonravivView Answer on Stackoverflow
Solution 11 - PythonMattiHView Answer on Stackoverflow
Solution 12 - PythonElijahView Answer on Stackoverflow