Evgenia Karunus
Evgenia Karunus

Reputation: 11202

Ruby app thinks client's IP address is always the same

Sinatra app.

<%= request.ip %>

gives 127.0.0.1 IP address if looked at from local server.
gives 83.245.226.68 IP address if looked at from Heroku server, no matter from which device.
So I guess it returns server's IP address and not client's. How do I find out what client's IP address is then? Did I misunderstand request.ip method?

Upvotes: 0

Views: 753

Answers (1)

maddin2code
maddin2code

Reputation: 1354

This happens when the HTTP Server in front of the Rack HTTP Server (e.g. used for load balancing, ssl, etc) is not forwarding the client IP address to the Rack HTTP Server. In that case you get the IP address of the HTTP Server.

This can be configured on HTTP Servers like Nginx and Apache and you get the client IP address in request.ip.

As far as I know Heroku is doing it in a way that the client IP address is in a header called "x-forwarded-for", which is a comma separated list of IP addresses, the last element is the client ip.

Sinatra:

env['HTTP_X_FORWARDED_FOR'].split(',').last

Rails:

request.headers['x-forwarded-for'].split(',').last

Upvotes: 5

Related Questions