Rails: Get Client IP address
Asked Answered
G

5

196

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']
Goins answered 16/12, 2010 at 21:19 Comment(0)
C
349

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

See: Get real IP address in local Rails development environment for some other things you can do with client server ip's.

Commit answered 16/12, 2010 at 21:35 Comment(0)
H
51

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.

Hegel answered 16/12, 2010 at 21:51 Comment(0)
C
11

Get client ip using command:

request.remote_ip
Coble answered 11/1, 2017 at 6:51 Comment(0)
U
4

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

Untouched answered 1/9, 2018 at 18:33 Comment(0)
C
2

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.

Caylacaylor answered 8/4, 2018 at 0:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.