Reputation: 978
In Ruby on Rails, how can I get the IP Address of a client? I want that when a user visits a certain page, Rails gets their ip address and displays it on the screen.
In my controller I've tried:
request.remote_ip
but it is returning ::1
which to my knowledge is IPv6. I would like to get the IPv4 address of the client. How can I achieve this? I would only need to do this once per client since I'm only checking the ip address of the first device that they use to visit my page.
Upvotes: 1
Views: 4633
Reputation: 2183
You can use either
request.ip
that returns the ip, whether it is a local proxy ip
address (localhost address) or not.request.remote_ip
is smarter and gets the ip address of the client
outside of local proxies and this is the best that is an interpretation of all the available IP address information and it will make a best-guess.(
request.remote_ip
)Determines originating IP address. REMOTE_ADDR is the standard but will fail if the user is behind a proxy. HTTP_CLIENT_IP and/or HTTP_X_FORWARDED_FOR are set by proxies so check for these if REMOTE_ADDR is a proxy. HTTP_X_FORWARDED_FOR may be a comma- delimited list in the case of multiple chained proxies; the last address which is not trusted is the originating IP.
Upvotes: 3
Reputation: 1845
Are you certain that ::1
is not sufficient? That is the local host; if you publish the site to anywhere requiring layer 3 transport it should render the appropriate IPv4 or IPv6 address respectively.
In short, if you disable your local IPv6 stack 127.0.0.1 would render.
Upvotes: 2