Skip to content

Commit

Permalink
gracefully fall back to other strategies when mac address cannot be d…
Browse files Browse the repository at this point in the history
…etermined (fixes sporkmonger#53)
  • Loading branch information
nwallace committed Jan 3, 2024
1 parent e4f0e05 commit 5502802
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 15 deletions.
27 changes: 13 additions & 14 deletions lib/uuidtools.rb
Original file line number Diff line number Diff line change
Expand Up @@ -631,22 +631,19 @@ def self.ip_path
# Call the ifconfig or ip command that is found
#
def self.ifconfig(all=nil)
# find the path of the ifconfig command
ifconfig_path = UUID.ifconfig_path

# if it does not exist, try the ip command
if ifconfig_path == nil
ifconfig_path = "#{UUID.ip_path} addr list"
# all makes no sense when using ip(1)
all = nil
end

all_switch = all == nil ? "" : "-a"
return `#{ifconfig_path} #{all_switch}` if not ifconfig_path == nil
command =
if ifconfig_path=UUID.ifconfig_path
"#{ifconfig_path}#{all ? " -a" : ""}"
elsif ip_path=UUID.ip_path
"#{ip_path} addr list"
end
`#{command}` if command
end

# Match and return the first Mac address found
def self.first_mac(instring)
return nil if instring.nil?

mac_regexps = [
Regexp.new("address:? (#{(["[0-9a-fA-F]{2}"] * 6).join(":")})"),
Regexp.new("addr:? (#{(["[0-9a-fA-F]{2}"] * 6).join(":")})"),
Expand Down Expand Up @@ -679,6 +676,7 @@ def self.first_mac(instring)
# Returns nil if a MAC address could not be found.
def self.mac_address
if !defined?(@@mac_address)
@@mac_address = nil
require 'rbconfig'

os_class = UUID.os_class
Expand All @@ -688,8 +686,9 @@ def self.mac_address
@@mac_address = UUID.first_mac `ipconfig /all`
rescue
end
else # linux, bsd, macos, solaris
@@mac_address = UUID.first_mac(UUID.ifconfig(:all))
elsif ifconfig_output=UUID.ifconfig(:all)
# linux, bsd, macos, solaris
@@mac_address = UUID.first_mac ifconfig_output
end

if @@mac_address != nil
Expand Down
8 changes: 7 additions & 1 deletion spec/uuidtools/mac_address_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,8 @@ def pending_if_root_required
:openbsd => openbsd_sample,
:linux => linux_sample,
:linux2 => linux_sample_2,
:linuxip => linux_ip_sample
:linuxip => linux_ip_sample,
:docker => nil
}

macs = {
Expand Down Expand Up @@ -451,4 +452,9 @@ module RbConfig
mac = UUIDTools::UUID.first_mac samples[:linuxip]
expect(mac).to eql(macs[:linuxip])
end

it "should return nil when unable to identify the mac address" do
mac = UUIDTools::UUID.first_mac nil
expect(mac).to be_nil
end
end

0 comments on commit 5502802

Please sign in to comment.