Onl*_*ere 4 ruby ip ruby-on-rails
这是我在Application控制器中编写的代码:
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :redirect_if_bolivia
private
def redirect_if_bolivia
if (bolivia_ip_block).includes? request.remote_ip
#redirect user to www.foo.com
end
end
def bolivia_ip_block
%w {
12.144.86.0 - 12.144.87.255
31.201.1.176 - 31.201.1.179
46.36.198.101 - 46.36.198.105
46.136.172.0 - 46.136.172.255
63.65.11.0 - 63.65.12.254
65.173.56.0 - 65.173.63.255
67.23.241.179 - 67.23.241.198
72.32.164.56 - 72.32.164.63
72.46.244.32 - 72.46.244.47
74.91.16.48 - 74.91.16.55
74.91.16.208 - 74.91.16.215
74.91.20.48 - 74.91.20.71
74.112.134.120 - 74.112.134.127
74.112.135.104 - 74.112.135.111
74.205.37.16 - 74.205.37.23
78.24.205.32 - 78.24.205.47
98.129.27.88 - 98.129.27.95
98.129.91.40 - 98.129.91.47
166.114.0.0 - 166.114.255.255
167.157.0.0 - 167.157.255.255
174.143.165.80 - 174.143.165.87
186.0.156.0 - 186.0.159.255
186.2.0.0 - 186.2.127.255
186.27.0.0 - 186.27.127.255
190.0.248.0 - 190.0.255.255
190.3.184.0 - 190.3.191.255
}
end
end
Run Code Online (Sandbox Code Playgroud)
那么基本上,检查一个request.remote_ip属于玻利维亚IP块的最简单方法是什么?
我不认为迭代每个块并吐出相应的IP,将其添加到数组是有效的.实际上,这将导致我为每个请求创建数千个条目的数组.
我相信这不是一个新问题,所以我喜欢这个解决方案.
也许我可以检查前三个八位字节是否匹配,然后它属于块?我如何在Ruby中进行简单的字符串比较?
您可以将子网转换为CIDR表示法,因为块不是任意的.然后你可以利用IPAddr #include
require 'ipaddr'
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :redirect_if_bolivia
private
def redirect_if_bolivia
if bolivian_blocks.any? { |block| block.include?(request.remote_ip) }
#redirect user to www.foo.com
end
end
def bolivian_blocks
%w{
12.144.86.0/23
31.201.1.176/30
}.map { |subnet| IPAddr.new subnet }
end
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1330 次 |
| 最近记录: |