Sha256: 425ba0f76fbf96b8f955e639d2da225f2b8907aa0efc81613eb9ea5966e5a970

Contents?: true

Size: 1.55 KB

Versions: 1

Compression:

Stored size: 1.55 KB

Contents

module Louis
  module Helpers
    # Calculate the bit mask for testing whether or not a mac_prefix matches.
    # This returns an integer with the upper X bits set where X is the mask
    # length.
    #
    # @param [String] prefix
    # @param [String] mask
    # @return [Fixnum]
    def calculate_mask(prefix, mask)
      mask_base = mask.nil? ? (clean_mac(prefix).length * 4) : mask.to_i
      (2 ** 48 - 1) - (2 ** (48 - mask_base) - 1)
    end

    # Returns the hex representing a full or partial MAC address with the
    # 'connecting' characters removed. Does nothing to ensure length.
    #
    # @param [String] mac
    # @return [String]
    def clean_mac(mac)
      mac.gsub(/[:-]/, '')
    end

    # Converts a hexidecimal version of a full or partial (prefix) MAC address
    # into it's integer representation.
    #
    # @param [String] mac
    def mac_to_num(mac)
      clean_mac(mac).ljust(12, '0').to_i(16)
    end

    # Handle parsing a line from the raw OUI file into it's associated lookup
    # table format. This will return nil if the line is poorly formatted, empty
    # or a comment.
    #
    # @param [String]
    # @return [Hash<String=>Object>]
    def line_parser(line)
      return unless (matches = OUI_FORMAT_REGEX.match(line))
      result = Hash[matches.names.zip(matches.captures)]

      {
        'mask'         => calculate_mask(result['prefix'], result['mask']),
        'prefix'       => mac_to_num(result['prefix']),
        'short_vendor' => result['short_vendor'],
        'long_vendor'  => result['long_vendor']
      }
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
louis-1.1.1 lib/louis/helpers.rb