Ruby Findings

digging for gems

ieeemac.rb, why let python have all the fun?

Posted by Bill Marquette Tue, 01 Apr 2008 04:07:00 GMT

I was a little bored tonight and thought I’d respond to a post over Happy Python with some code. Thanks for the inspiration Matt!

ruby>> require 'ieeemac'
# => true  
ruby>> macs = Mac.find_macs `ifconfig -a`
# => [#<Mac:0x1357f40 @mac=["00", "16", "cb", "95", "13", "50"]>, #<Mac:0x1357f2c @mac=["00", "16", "cb", "ff", "fe", "5d"]>, #<Mac:0x1357d74 @mac=["00", "17", "f2", "41", "ec", "ec"]>, #<Mac:0x1357c20 @mac=["00", "50", "56", "c0", "00", "08"]>, #<Mac:0x1357ae0 @mac=["00", "50", "56", "c0", "00", "01"]>, #<Mac:0x135798c @mac=["00", "1c", "42", "00", "00", "00"]>, #<Mac:0x13577e8 @mac=["00", "1c", "42", "00", "00", "01"]>]  
ruby>> macs[0].to_format :cisco
# => "0016.cb95.1350"  
ruby>> macs[0].to_cisco
# => "0016.cb95.1350"  

Read the rest of this post for the full class.

# We got your MAC manipulation here
class Mac
  #bare:    001122334455
  #windows: 00-11-22-33-44-55
  #unix?:   00:11:22:33:44:55
  #cisco:   0011.2233.4455  
  VALID_MACS=/[0-9a-f]{12}|[0-9a-f]{2}[:-][0-9a-f]{2}[:-][0-9a-f]{2}[:-][0-9a-f]{2}[:-][0-9a-f]{2}[:-][0-9a-f]{2}|[0-9a-f]{4}\.[0-9a-f]{4}\.[0-9a-f]{4}/

  def initialize(str)
    if ismac?(str)
      # Convert to internal octet representation
      @mac = str.gsub(/[.:-]/,'').scan(/../)
    else
      raise ArgumentError, "Invalid MAC", caller
    end
  end

  # return all the valid MAC's in a given string as an array
  def self.find_macs(str)
    macs = str.scan VALID_MACS
    ret = []
    macs.each { |mac| ret << Mac.new(mac) }
    ret
  end

  def to_format(fmt)
    # Convert to symbol for ease of use
    fmt = fmt.to_sym
    case fmt
    when :bare
      to_bare
    when :windows
      to_windows
    when :unix
      to_unix
    when :cisco
      to_cisco
    end
  end

  def ismac?(str)
    VALID_MACS =~ str
  end

  def to_bare
    @mac.join('')
  end
  alias :mac :to_bare

  def to_windows
    @mac.join('-')
  end
  def to_unix
    @mac.join(':')
  end
  def to_cisco
    sprintf("%s%s.%s%s.%s%s", @mac[0],@mac[1],@mac[2],@mac[3],@mac[4],@mac[5])
  end
end

# macs = Mac.find_macs(`ifconfig -a`)
# macs.each do |mac|
#   puts "BARE:    #{mac.to_format(:bare)}"
#   puts "WINDOWS: #{mac.to_format(:windows)}"
#   puts "UNIX:    #{mac.to_format(:unix)}"
#   puts "CISCO:   #{mac.to_format(:cisco)}"
# end

Posted in | 2 comments |


html>