-1

How to get in a decorator function in Flask the IP address and port of the client that sent the request ?

from flask import Flask, request, jsonify
from functools import wraps
app = Flask(__name__)

def check_auth(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        print(request)
        ###  Here I need the IP address and port of the client
        return f(*args, **kwargs)
    return decorated_function

@app.route('/test', methods=['POST'])
@check_auth
def hello():
    json = request.json
    json['nm'] = 'new name2'
    jsonStr = jsonify(json)
    return jsonStr
ps0604
  • 1,513
  • 20
  • 113
  • 274

1 Answers1

5

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
kellymandem
  • 1,509
  • 2
  • 15
  • 23
amanb
  • 4,641
  • 2
  • 17
  • 36