I'm using the geocoder gem which has the ability to pick up IP address from an http request. from the documentation:
Geocoder adds a +location+ method to the standard <tt>Rack::Request</tt> object so you can easily look up the location of any HTTP request by IP address. For example, in a Rails controller or a Sinatra app:
# returns Geocoder::Result object
result = request.location
I put
@result = request.location
in my controller and then in my view
<%= @result %>
However, I got this.
#<Geocoder::Result::Freegeoip:0x00000102dc7758>
I then tried
<%= @result.to_s %>
but it didn't change anything.
Any ideas?
To get the IP of a client use request.ip
. It's more correct way of getting the IP, especially when your user is behind a proxy . So, it's simple as:
request.ip
Here's its source:
# File lib/rack/request.rb, line 256
def ip
if addr = @env['HTTP_X_FORWARDED_FOR']
(addr.split(',').grep(/\d\./).first || @env['REMOTE_ADDR']).to_s.strip
else
@env['REMOTE_ADDR']
end
end
If all you need is an IP address, then you can get that from the request headers. It may not be perfectly accurate due to spoofing, but from a quick look at some of the header values, I found the REMOTE_ADDR to contain mine. Just put this in a controller. If someone else can recommend other or better values to use, please let us know.
request.headers['REMOTE_ADDR']
I actually tried checking for HTTP_X_FORWARDED_FOR, but it didn't exist in the headers. Perhaps webrick doesn't use it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.