class MacAddr

Constants

RE

Public Class Methods

cmd_ifaddrs() click to toggle source
# File lib/rmacaddr.rb, line 62
def self.cmd_ifaddrs
    cmds = '/sbin/ifconfig', '/bin/ifconfig', 'ifconfig', 'ipconfig /all', 'cat /sys/class/net/*/address'

    output = nil
    cmds.each do |cmd|
      stdout = `#{cmd}` rescue next
      next unless stdout and stdout.size > 0
      output = stdout and break
    end
    raise "all of #{ cmds.join ' ' } failed" unless output

    @mac_address = cmd_parse(output)
end
cmd_parse(output) click to toggle source
# File lib/rmacaddr.rb, line 76
def self.cmd_parse(output)
  lines = output.split(/\n/)

  candidates = lines.select{|line| line =~ RE}
  raise 'no mac address candidates' unless candidates.first
  candidates = candidates.map{|c| c[RE].strip}

  raise 'no mac address found' if candidates.empty?

  candidates
end
from_getifaddrs() click to toggle source
# File lib/rmacaddr.rb, line 32
def self.from_getifaddrs
  return unless Socket.respond_to? :getifaddrs

  link   = Socket::PF_LINK   if Socket.const_defined? :PF_LINK
  packet = Socket::PF_PACKET if Socket.const_defined? :PF_PACKET
  interface_packet_family = link || packet


  interfaces = Socket.getifaddrs.select do |addr|
    addr.addr.pfamily == interface_packet_family
  end

  mac_list, =
    if Socket.const_defined? :PF_LINK then
      interfaces.map do |addr|
        addr.addr.getnameinfo
      end.select do |m,|
        !m.empty?
      end
    elsif Socket.const_defined? :PF_PACKET then
      interfaces.map do |addr|
        addr.addr.inspect_sockaddr[/hwaddr=([\h:]+)/, 1]
      end.select do |mac_addr|
        mac_addr != '00:00:00:00:00:00'
      end
    end

  mac_list.select{|m| !m.empty?}
end
list() click to toggle source
# File lib/rmacaddr.rb, line 24
def self.list
  @list ||= parse_list
end
parse_list() click to toggle source
# File lib/rmacaddr.rb, line 28
def self.parse_list
  from_getifaddrs || cmd_ifaddrs
end