
Web applications can receive requests directly, via a CGI process, through proxy servers, relayed from front-end web servers, and so on. This can complicate how you might find out where the request originated if you, for example, wanted to limit an online poll to one vote per IP address. Luckily, Rails consolidates most of the ways to get this info into a single convenience method on the request object for us.
The Convenience Method: #remote_ip
Without the request.remote_ip method, you’d have to look for specific headers that are used to carry this data in the HTTP request beyond the server where the actual client’s connection was terminated.
Rails’ request.remote_ip method is pretty smart: it looks for and parses the headers HTTP_CLIENT_IP, HTTP_X_FORWARDED_FOR and REMOTE_ADDR and parse the value which are commonly used for this purpose.
Example Rails Code
In RAILS_ROOT/app/controllers/show_my_ip_controller.rb:
class ShowMyIpController < ApplicationController
def index
@client_ip = request.remote_ip
end
end
In RAILS_ROOT/app/views/show_my_ip/index.html.erb:
Your IP address is <%= @client_ip %>
Further Reading
The request.remote_ip method is documented in the Rails Framework rdocs.
Feedback and Article Ideas
Want to see a topic explored here? Send Me a Message.
Do you have any advice on how I can take this a step further? I am looking to limit a given user to one vote per session but I’m not sure how to achieve this. I’d appreciate any help you can offer. Thanks for your time.
Aaron, that’s a good idea for an article
See How to limit users to one vote per IP address.
[...] I just found out that request.remote_ip does the same as my function. Unfortunately, it only works in Rails 2.0. [...]
[...] I just found out that request.remote_ip does the same as my determine_ip-function. Unfortunately, it only works in [...]
thanks dude, this was actually useful.
[...] How to obtain the IP address of the current user | kev.in: [...]