简体   繁体   中英

Get Client IP Address in Rails and Output to View

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.

You can use either

  1. request.ip that returns the ip, whether it is a local proxy ip address (localhost address) or not.
  2. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM