Ruby-on-rails 如何使用 Rails 获取客户端 IP 和服务器 IP
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1226959/
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
How to get client IP and Server IP using Rails
提问by Senthil Kumar Bhaskaran
Can anyone please help how to get client IP and also server IP using Ruby on Rails?
任何人都可以帮助如何使用Ruby on Rails获取客户端IP和服务器IP吗?
采纳答案by Senthil Kumar Bhaskaran
Thanks: karim79 and Titanous.
谢谢:karim79 和 Titanous。
Write the code in Controller
在控制器中编写代码
For Client IP:
对于客户端 IP:
request.remote_ip
@remote_ip = request.env["HTTP_X_FORWARDED_FOR"]
For Server IP:
对于服务器 IP:
require 'socket'
def local_ip
orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true # turn off reverse DNS resolution temporarily
UDPSocket.open do |s|
s.connect '64.233.187.99', 1
s.addr.last
end
ensure
Socket.do_not_reverse_lookup = orig
end
回答by karim79
From your controller:
从您的控制器:
request.remote_ip
If you are using apache in front of a mongrel, then remote_ip will return the source address of the request, which in this case will be local host because the Apache web server is making the request, so instead put this in your controller:
如果您在 mongrel 前面使用 apache,则 remote_ip 将返回请求的源地址,在这种情况下将是本地主机,因为 Apache Web 服务器正在发出请求,因此将其放在您的控制器中:
@remote_ip = request.env["HTTP_X_FORWARDED_FOR"]
To get the server IP see:
要获取服务器 IP,请参阅:

