Sha256: b34de7e475d81d9a376f193a992006d449567a17714b8011864686990ea5c3d6

Contents?: true

Size: 1.25 KB

Versions: 4

Compression:

Stored size: 1.25 KB

Contents

module SeventeenMon
  class IP
    attr_reader :ip

    def initialize(ip: nil, address: nil, protocol: nil)
      @ip = ip || Socket.getaddrinfo(address, protocol)[0][3]
    end

    def four_number
      @four_number ||= begin
        fn = ip.split(".").map(&:to_i)
        raise "ip is no valid" if fn.length != 4 || fn.any?{ |d| d < 0 || d > 255}
        fn
      end
    end

    def ip2long
      @ip2long ||= ::IPAddr.new(ip).to_i
    end

    def packed_ip
      @packed_ip ||= [ ip2long ].pack 'N'
    end

    def find
      tmp_offset = four_number[0] * 4
      start = IPDB.instance.index[tmp_offset..(tmp_offset + 3)].unpack("V")[0] * 8 + 1024

      index_offset = nil

      while start < IPDB.instance.max_comp_length
        if IPDB.instance.index[start..(start + 3)] >= packed_ip
          index_offset = "#{IPDB.instance.index[(start + 4)..(start + 6)]}\x0".unpack("V")[0]
          index_length = IPDB.instance.index[(start + 7)].unpack("C")[0]
          break
        end
        start += 8
      end

      return "N/A" unless index_offset

      result = IPDB.instance.seek(index_offset, index_length).map do |str|
        ::Iconv.conv("UTF-8", "UTF-8", str)
      end

      {
        country: result[0],
        city: result[1]
      }
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
seventeen_mon-0.0.4 lib/seventeen_mon/ip.rb
seventeen_mon-0.0.3 lib/seventeen_mon/ip.rb
seventeen_mon-0.0.2 lib/seventeen_mon/ip.rb
seventeen_mon-0.0.1 lib/seventeen_mon/ip.rb