39

This is a really simple question, but I cannot find any mention of this, anywhere..

How do I get the client's IP address from in Sinatra?

get '/' do
    "Your IP address is #{....}"
end
dbr
  • 165,801
  • 69
  • 278
  • 343
  • 1
    Err, oh, it's in `@env['REMOTE_ADDR']` - I had checked the `@env.inspect` output by searching for "127.0.0.1", but it was showing the IPv6 `::1` address so I missed it... Anyone feel free to post that so I can accept it without the 48-hour wait.. (free rep! :P) – dbr Aug 23 '09 at 19:27

2 Answers2

74

Sinatra provides a request object, which is the interface to the client request data that you should be using.

Using request.ip is the preferred method to find the client's IP address:

get '/' do
  "Your IP address is #{request.ip}"
end
Matteo Ragni
  • 2,837
  • 1
  • 20
  • 34
user229044
  • 232,980
  • 40
  • 330
  • 338
18

I was coming to post the answer anyway.. so:

get '/' do
"Your IP address is #{ @env['REMOTE_ADDR'] }"
end

Sinatra uses the Rack::Request API, so you can use a lot of things available in it.
Also a link to the Sinatra doc's.

Brian Gianforcaro
  • 26,564
  • 11
  • 58
  • 77
  • 2
    Hm, the Rack::Request API mentions an `ip` method, which handles the `HTTP_X_FORWARDED_FOR` as well, is there a way to call this from Sinatra? – dbr Aug 23 '09 at 20:38
  • 1
    you should be able to just do #{ @env['HTTP_X_FORWARDED_FOR'] } I have never tested this though, so I'm not positive. – Brian Gianforcaro Aug 23 '09 at 20:57
  • 7
    you can do request.ip directly, as well. get "/" do; "your IP: #{request.ip}"; end – bantic Aug 10 '10 at 15:18
  • 2
    see: https://github.com/chneukirchen/rack/blob/master/lib/rack/request.rb#L315 ... very risky approach here – Sam Saffron Jun 28 '12 at 06:19