Class: OuiSearch

Inherits:
Object
  • Object
show all
Defined in:
lib/ouisearch.rb

Constant Summary collapse

URL =
"www.ieee.org/netstorage/standards/oui.txt"
URLHOST =
"http://www.ieee.org"
URLPATH =
"/netstorage/standards/oui.txt"
CACHE =
"#{ENV['HOME']}/.oui"
REG =
/^\s+(..)-(..)-(..)\s+\(hex\)\s+(.+)$/

Instance Method Summary collapse

Constructor Details

#initialize(args = {}) ⇒ OuiSearch

Returns a new instance of OuiSearch.



14
15
16
17
18
19
20
# File 'lib/ouisearch.rb', line 14

def initialize args={}
  @reload = args[:reload] || false
  @debug = args[:debug] || false
  @ouis = nil
  fetch_cache
  load_cache
end

Instance Method Details

#dprint(str) ⇒ Object



74
75
76
77
# File 'lib/ouisearch.rb', line 74

def dprint str
  return nil unless @debug
  print "#{str}\n"
end

#execute(oui) ⇒ Object



22
23
24
25
26
27
28
29
# File 'lib/ouisearch.rb', line 22

def execute oui
  vendor = @ouis[oui.upcase]
  if vendor
    return vendor.strip
  else
    return "<UNKNOWN>"
  end
end

#fetch_cacheObject



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/ouisearch.rb', line 31

def fetch_cache
  if File.exists?(CACHE) and @reload == false
    # nothing to do
    return
  end

  if @reload
    dprint "force cache update ($HOME/.oui) ...\n"
  else
    dprint "no cache ($HOME/.oui) found. creating cache ...\n"
  end

  File.open(CACHE, "w") do |f|
    @ouis = http_get_ouis()
    f.write(Marshal.dump(@ouis))
  end

  dprint "cache created (#{@ouis.length} entries)\n"
end

#http_get_ouisObject



51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/ouisearch.rb', line 51

def http_get_ouis
  ouis = {}
  conn = Faraday.new(:url => URLHOST)
  response = conn.get(URLPATH)
  raise "failed to fetch oui" if response.status != 200
  response.body.split("\n").each do |line|
    match = line.match(REG)
    next unless match
    oui = match[1] + ":" + match[2] + ":" + match[3]
    vendor = match[4]
    ouis[oui.upcase] = vendor
  end
  return ouis
end

#load_cacheObject



66
67
68
69
70
71
72
# File 'lib/ouisearch.rb', line 66

def load_cache
  return @ouis if @ouis # already fetched
  File.open(CACHE, "r") do |f|
    @ouis = Marshal.load(f.read)
  end
  dprint "cache reloading done (#{@ouis.length} entries)\n"
end