Created
August 31, 2010 09:35
-
-
Save macros/558791 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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