How to obtain the IP address of the current user

Some house address

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


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.