Get Ip Address of Visitors Using Flask for Python

Get IP address of visitors using Flask for 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.

Python, Flask client ip address

How do you deploy the flask application?

I guess you deploy your app via a reverse-proxy server like nginx, right?

If you did that then request.remote_addr is the address of your server because your server sent client's request to your application and sent the response to the client.

To fix this, see: http://flask.pocoo.org/docs/0.11/deploying/wsgi-standalone/#proxy-setups

Get IP address and port in Flask decorator function

You can use Flask's request.environ() function to get the Remote port and IP Address for the client:

from flask import request
from functools import wraps

def check_auth(f):
@wraps(f)
def decorated_function(*args, **kwargs):
print(request)
### Here I need the IP address and port of the client
print("The client IP is: {}".format(request.environ['REMOTE_ADDR']))
print("The client port is: {}".format(request.environ['REMOTE_PORT']))
return f(*args, **kwargs)
return decorated_function

The decorator prints something like:

The client IP is: 127.0.0.1
The client port is: 12345


Related Topics



Leave a reply



Submit