Skip to content

Instantly share code, notes, and snippets.

@tekei
Created August 28, 2012 23:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tekei/3505432 to your computer and use it in GitHub Desktop.
Save tekei/3505432 to your computer and use it in GitHub Desktop.
rubyでIPレンジの判定
# 「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