Search code examples
pythonhttpflasktcpwerkzeug

Determine the client port in a Flask request


In a Flask server, is it possible to determine the remote port of the client?

I see request.remote_addr https://flask.palletsprojects.com/en/1.1.x/api/#flask.Request.remote_addr for the client's IP address, but I'm looking to see if I can determine the client's port.

(I'm using a Flask server as part of a test, testing an HTTP client I'm working on. The client should use re-use connections between requests, so to get evidence of this, am trying to check that the same client port is used across requests. Not a perfect test admittedly, but it is likely good enough for my purposes.)


Solution

  • It's in the environ element of the request object:

    request.environ['REMOTE_PORT']