How to obtain the IP address of the current user 6

Posted by Kev.in on August 26, 2007

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
  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.

Trackbacks

Use this link to trackback from your own site.

Comments

Leave a response

  1. Aaron J. Fri, 18 Jan 2008 02:07:17 PST

    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.

  2. Kevin Fri, 18 Jan 2008 09:59:03 PST

    Aaron, that’s a good idea for an article :) See How to limit users to one vote per IP address.

  3. Finding the correct IP address in Rails Thu, 03 Apr 2008 05:48:50 PDT

    [...] I just found out that request.remote_ip does the same as my function. Unfortunately, it only works in Rails 2.0. [...]

  4. [...] I just found out that request.remote_ip does the same as my determine_ip-function. Unfortunately, it only works in [...]

  5. greg Thu, 14 Aug 2008 01:14:49 PDT

    thanks dude, this was actually useful.

  6. [...] How to obtain the IP address of the current user | kev.in: [...]

Comments