Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get my MAC Address programmatically with Ruby

Tags:

macos

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?

like image 750
mcass20 Avatar asked Jan 06 '12 17:01

mcass20


2 Answers

I don't think there is any Ruby built-in function to retrieve that address; you'll likely have to make a system call to list the value (e.g. ifconfig on UNIX, ipconfig /all on Win32) and parse the output as necessary.

Something like this (untested 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
like image 169
maerics Avatar answered Nov 19 '22 22:11

maerics


There is a gem called macaddr that does this, but basically it's parsing the output of the system's ifconfig. You can see the thread when it was being developed at http://www.ruby-forum.com/topic/113956

like image 28
the Tin Man Avatar answered Nov 19 '22 22:11

the Tin Man