Ramyavjr
Ramyavjr

Reputation: 319

Getting client ip address in flask

I am trying to get the client ip at the server Y in the following scenario,

client requests server X which forwards the request to server Y.

And the return flow is Y->X->client

'REMOTE_ADDR' in the http header(actually i get it from request.environ['REMOTE_ADDR']) has the ip of server X. From where can i get the ip of the client at server Y ?

UPDATE:

X has a public ip. Y is in a private network and is inaccessible outside. Now i am using a client in the same private network and i request X via the public network.

I just want to know if the header already has what i need without manipulating the header at X to include ip of client.

Upvotes: 1

Views: 4115

Answers (2)

DazWorrall
DazWorrall

Reputation: 14210

If your application is behind a proxy then the remote address of the request will appear to your application to be from the proxy, not the actual client.

There is no provision in the http spec to pass on the 'real' address but the de-facto standard for doing this is by having your proxy set an X-Forwarded-For header

Werkzeug provides a fixer to help with this, and there's an example detailed in the Flask docs, request.remote_addr should then be what you expect

Upvotes: 2

Markus Unterwaditzer
Markus Unterwaditzer

Reputation: 8244

Despite your claims, X is basically a proxy, since it makes its own request to Y, based on a request the user makes. So it's perfectly valid that REMOTE_ADDR is the one of X.

You will have to add a custom header to X's requests, like X-Original-User-IP to make the user's IP available to Y. You can use ProxyFix for this if you want, it will rewrite X-Forwarded-For to REMOTE_ADDR

You should make sure Y is only available to X and cannot be accessed directly. Otherwise one could spoof his IP address simply by sending that custom header.

Upvotes: 0

Related Questions