Created
August 28, 2012 23:50
-
-
Save tekei/3505432 to your computer and use it in GitHub Desktop.
rubyでIPレンジの判定
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 「192.168.0.0/24」の様なIPレンジ指定のテキストファイルを読み込み、 | |
# 該当IPアドレスかどうかをチェックする。 | |
# | |
# (制約) ネットワークアドレス長を9以上で指定する必要があります。 | |
# | |
# ・使い方 | |
# initialize - テキストファイルをパラメータとして指定 | |
# contain? - IPアドレスが含まれていたら true | |
class IPFilter | |
def initialize(ipfile) | |
@gate = {} | |
(0...256).each {|i| @gate[i] = []} | |
IO.foreach(ipfile) do |line| | |
s = line.split(/[\.\/]/).map {|c| c.to_i} | |
@gate[s[0]] << [s[0...4].pack("C*").unpack("N")[0], s[4]] | |
end | |
end | |
def contain?(ip) | |
i = ip.split('.').map{|c| c.to_i} | |
ip_addr = i.pack("C*").unpack("N")[0] | |
@gate[i[0]].each do |list| | |
return true if (ip_addr & (0xFFFFFFFF - (0xFFFFFFFF >> list[1]))) == list[0] | |
end | |
false | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment