Rails: Get Client IP address

Ruby on-RailsClientIp Address

Ruby on-Rails Problem Overview


In Rails, what's the best way to get the ip address of the client connecting to the server?

Here are two ways I've found:

request.remote_ip
request.env['HTTP_X_REAL_IP']

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

I would just use the request.remote_ip that's simple and it works. Any reason you need another method?

See: https://stackoverflow.com/questions/3887943/ip-address-in-rails for some other things you can do with client server ip's.

Solution 2 - Ruby on-Rails

request.remote_ip is an interpretation of all the available IP address information and it will make a best-guess. If you access the variables directly you assume responsibility for testing them in the correct precedence order. Proxies introduce a number of headers that create environment variables with different names.

Solution 3 - Ruby on-Rails

Get client ip using command:

request.remote_ip

Solution 4 - Ruby on-Rails

I found request.env['HTTP_X_FORWARDED_FOR'] very useful too in cases when request.remote_ip returns 127.0.0.1

Solution 5 - Ruby on-Rails

For anyone interested and using a newer rails and the Devise gem: Devise's "trackable" option includes a column for current/last_sign_in_ip in the users table.

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
Questionma11hew28View Question on Stackoverflow
Solution 1 - Ruby on-RailsloosecannonView Answer on Stackoverflow
Solution 2 - Ruby on-RailstadmanView Answer on Stackoverflow
Solution 3 - Ruby on-Railspuneet18View Answer on Stackoverflow
Solution 4 - Ruby on-RailsalikkView Answer on Stackoverflow
Solution 5 - Ruby on-RailsNorseGaudView Answer on Stackoverflow