How to get MAC address programmatically with Ruby

I am writing a script that needs to know what the MAC address of the host computer is.

Does anyone know how to do this?

+5
source share
2 answers

I do not think that there is a built-in Ruby function to get this address; you may have to make a system call to list the value (for example, ifconfigon UNIX, ipconfig /allon Win32) and analyze the output as needed.

Something like this (unverified pseudocode):

def mac_address
  platform = RUBY_PLATFORM.downcase
  output = `#{(platform =~ /win32/) ? 'ipconfig /all' : 'ifconfig'}`
  case platform
    when /darwin/
      $1 if output =~ /en1.*?(([A-F0-9]{2}:){5}[A-F0-9]{2})/im
    when /win32/
      $1 if output =~ /Physical Address.*?(([A-F0-9]{2}-){5}[A-F0-9]{2})/im
    # Cases for other platforms...
    else nil
  end
end
+4
source

There is a stone called macaddrthat does this, but it basically analyzes the output of the system ifconfig. You can see the stream when it was developed at http://www.ruby-forum.com/topic/113956

+3
source

All Articles