Class: IpToAsn

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

Instance Method Summary collapse

Constructor Details

#initializeIpToAsn

Returns a new instance of IpToAsn.



7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/main.rb', line 7

def initialize
  @index = chunk_index
  @cache = {}
  @chunk_dir = './chunks'
  @reserved_ranges = {
    IPAddr.new('10.0.0.0/8') => 'RFC1918 Private',
    IPAddr.new('172.16.0.0/12') => 'RFC1918 Private',
    IPAddr.new('192.168.0.0/16') => 'RFC1918 Private',
    IPAddr.new('0.0.0.0/8') => 'Current Network',
    IPAddr.new('127.0.0.0/8') => 'Loopback',
    IPAddr.new('169.254.0.0/16') => 'Link Local'
  }
end

Instance Method Details

#lookup(ip_str) ⇒ Object

rubocop:disable Metrics/AbcSize



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/main.rb', line 21

def lookup(ip_str) # rubocop:disable Metrics/AbcSize
  reserved_range_name = find_range(
    ranges: @reserved_ranges,
    ip_address: ip_str
  )

  return { as_number: 0, country_code: 'XX', as_name: reserved_range_name } unless reserved_range_name.nil?

  chunk_name = binary_search(@index, ip_str).first
  return nil if chunk_name.nil?

  if @cache[chunk_name].nil?
    require_relative "#{@chunk_dir}/#{chunk_name}.rb"
    @cache[chunk_name] = send "chunk_#{chunk_name}".to_sym
  end

  result = binary_search(@cache[chunk_name], ip_str)
  return nil if result.empty?

  { as_number: result[0], country_code: result[1], as_name: result[2] }
end