Skip to content

Commit

Permalink
Fix MiqEnvironment.local_ip_address to not prefer loopback
Browse files Browse the repository at this point in the history
`#local_ip_address` currently prefers loopback addresses since it
filters out "private" addresses and not "loopback" addresses.

IMO we should prefer public, then private, then loopback.
  • Loading branch information
agrare committed Jan 28, 2021
1 parent 4878f21 commit 88593d3
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
12 changes: 10 additions & 2 deletions lib/miq_environment.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,18 @@ def self.fully_qualified_domain_name
Socket.gethostbyname(Socket.gethostname).first
end

# Return the local IP v4 address of the local host, ignoring private addresses.
# Return the local IP v4 address of the local host
#
def self.local_ip_address
Socket.ip_address_list.detect { |addr| addr.ipv4? && !addr.ipv4_private? }&.ip_address
ipv4_addrs = Socket.ip_address_list.select(&:ipv4?)

# Prioritize "public" aka non-loopback non-private addresses first, then
# prefer private addresses, then take whatever we can get
local_addr = ipv4_addrs.detect { |ip| !ip.ipv4_loopback? && !ip.ipv4_private? }
local_addr ||= ipv4_addrs.detect { |ip| !ip.ipv4_loopback? }
local_addr ||= ipv4_addrs.first

local_addr&.ip_address
end

class Command
Expand Down
2 changes: 1 addition & 1 deletion spec/lib/miq_environment_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
end

example "local_ip_address" do
expect(described_class.local_ip_address).to eq(`hostname -i`.chomp.split.first)
expect(described_class.local_ip_address).to be_in(Socket.ip_address_list.map(&:ip_address))
end
end

Expand Down

0 comments on commit 88593d3

Please sign in to comment.