Skip to content

Instantly share code, notes, and snippets.

@macros
Created August 31, 2010 09:35
Show Gist options
  • Save macros/558791 to your computer and use it in GitHub Desktop.
Save macros/558791 to your computer and use it in GitHub Desktop.
def get_ifs_and_addrs
interfaces = {}
curr_inf = ""
IO.popen("ip a").each do |line|
if line =~ /^\d+?: (.*):/
interfaces[$1] = Array.new
curr_inf = $1
end
if line =~ /\s+inet\s(.*)\//
interfaces[curr_inf] << $1
end
end
return interfaces
end
def local_ip
require 'ipaddr'
local_space = IPAddr.new("10.0.0.0/8")
# Return the loopback is exists
interfaces = get_ifs_and_addrs
if interfaces["lo"] && interfaces["lo"].size > 1
interfaces["lo"].each do |addr|
return addr if local_space.include?(addr)
end
end
# Use the default ip if it is local
return node[:ipaddress] if local_space.include?(node[:ipaddress])
interfaces.sort.each do |iface,addrs|
addrs.each do |addr|
return addr if local_space.include?(addr)
end
end
return node[:ipaddress]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment