blackbaka
blackbaka

Reputation: 65

How to use Flask get client's port?

I'm trying to build a simple torrent-tracker with Flask, but I meet a problem.

If client in NAPT network, the port, which included in request is incorrect. I want to get client connect port with Flask (In PHP like this function: $_SERVER['REMOTE_PORT']).

How to get client port with Flask?

Upvotes: 5

Views: 5564

Answers (3)

Moshe Globus
Moshe Globus

Reputation: 1

You can print(request.environ) to see its keys. For example you can get it by origin = request.environ.get('HTTP_ORIGIN') port = origin.split(":")[-1]

Upvotes: 0

Ph3n0x
Ph3n0x

Reputation: 306

If Flask is behind a reverse proxy,

request.environ.get('REMOTE_PORT')

will not give you what you want, you are going to get the port used by the reverse proxy.

If using Nginx, add this bold line to your config file:

server {
    listen 80;
    server_name _;
    location / {
        proxy_pass ...;
        proxy_set_header WHATEVER $remote_port;
    } 
} 

Then you can get the client port with :

request.headers.get('WHATEVER')

Upvotes: 3

r-m-n
r-m-n

Reputation: 15120

You can get it from request.environ

request.environ.get('REMOTE_PORT')

Upvotes: 5

Related Questions