如何使用Ruby以编程方式获取我的MAC地址

mca*_*s20 5 ruby macos

我正在编写一个脚本,需要知道主机的MAC地址是什么.

有谁知道如何做到这一点?

mae*_*ics 4

我不认为有任何 Ruby 内置函数可以检索该地址;您可能需要进行系统调用来列出该值(例如,ifconfig在 UNIX 上、ipconfig /allWin32 上)并根据需要解析输出。

像这样的东西(未经测试的伪代码):

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
Run Code Online (Sandbox Code Playgroud)