Ruby-on-rails Rails:获取客户端 IP 地址

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4465476/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:54:50  来源:igfitidea点击:

Rails: Get Client IP address

ruby-on-railsclientip-address

提问by ma11hew28

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

在 Rails 中,获取连接到服务器的客户端的 IP 地址的最佳方法是什么?

Here are two ways I've found:

这是我找到的两种方法:

request.remote_ip
request.env['HTTP_X_REAL_IP']

回答by loosecannon

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

我只会使用request.remote_ip那很简单而且很有效的方法。你有什么理由需要另一种方法吗?

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

请参阅:在本地 Rails 开发环境中获取真实 IP 地址,了解您可以使用客户端服务器 ip 执行的其他一些操作。

回答by tadman

request.remote_ipis 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.

request.remote_ip是对所有可用 IP 地址信息的解释,它将做出最佳猜测。如果您直接访问变量,则您承担以正确的优先顺序测试它们的责任。代理引入了许多创建具有不同名称的环境变量的头文件。

回答by puneet18

Get client ip using command:

使用命令获取客户端IP:

request.remote_ip

回答by alikk

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

我发现request.env['HTTP_X_FORWARDED_FOR']request.remote_ip返回的情况下也非常有用127.0.0.1

回答by NorseGaud

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.

对于任何有兴趣并使用更新的 rails 和 Devise gem 的人:Devise 的“可跟踪”选项包括用户表中 current/last_sign_in_ip 的列。