How to get client IP and Server IP using Rails

Ruby on-RailsIp

Ruby on-Rails Problem Overview


Can anyone please help how to get client IP and also server IP using Ruby on Rails?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

From your controller:

request.remote_ip

If you are using apache in front of a mongrel, then remote_ip will return the source address of the request, which in this case will be local host because the Apache web server is making the request, so instead put this in your controller:

@remote_ip = request.env["HTTP_X_FORWARDED_FOR"]

To get the server IP see:

https://stackoverflow.com/questions/42566/getting-the-hostname-or-ip-in-ruby-on-rails

Solution 2 - Ruby on-Rails

Thanks: karim79 and Titanous.

Write the code in Controller

For Client IP:

request.remote_ip

@remote_ip = request.env["HTTP_X_FORWARDED_FOR"]

For Server IP:

require 'socket'

def local_ip
  orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true  # turn off reverse DNS resolution temporarily

  UDPSocket.open do |s|
    s.connect '64.233.187.99', 1
    s.addr.last
  end
ensure
  Socket.do_not_reverse_lookup = orig
end

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSenthil Kumar BhaskaranView Question on Stackoverflow
Solution 1 - Ruby on-Railskarim79View Answer on Stackoverflow
Solution 2 - Ruby on-RailsSenthil Kumar BhaskaranView Answer on Stackoverflow