-
Notifications
You must be signed in to change notification settings - Fork 3
sandbox listing network interfaces
tora edited this page Feb 6, 2012
·
1 revision
module Castoro module IfConfig # This module works with both CentOS and OpenSolaris. IFCONFIG_COMMAND = '/sbin/ifconfig -a' def network_interfaces Hash.new.tap do |h| IO.popen IFCONFIG_COMMAND do |pipe| while line = pipe.gets do line =~ /\A(\w+)\W/ and h[ (dev = $1) ] = {} line =~ /inet\D+(\d+\.\d+\.\d+\.\d+)/ and h[dev][:inet] = $1 line =~ /(?:Bcast|broadcast)\D+(\d+\.\d+\.\d+\.\d+)/ and h[dev][:broadcast] = $1 line =~ /Mask\D+(\d+\.\d+\.\d+\.\d+)/ and h[dev][:netmask] = $1 line =~ /netmask\s+([0-9a-f]+)/ and h[dev][:netmask] = convert_hex_into_dec($1) end end end end private def convert_hex_into_dec value n = value.hex d = n & 0xff c = (n >> 8) & 0xff b = (n >> 8) & 0xff a = (n >> 8) & 0xff sprintf "%d.%d.%d.%d", a, b, c, d end module_function :network_interfaces, :convert_hex_into_dec end end if $0 == __FILE__ module Castoro IfConfig.network_interfaces.each do |k, v| print "#{k} => #{v}\n" end end end __END__ centos$ /usr/local/bin/ruby list_nic.rb eth0 => {:inet=>"192.168.223.10", :broadcast=>"192.168.223.255", :netmask=>"255.255.255.0"} eth1 => {:inet=>"192.168.224.10", :broadcast=>"192.168.224.255", :netmask=>"255.255.255.0"} lo => {:inet=>"127.0.0.1", :netmask=>"255.0.0.0"} ... opensolaris$ /usr/local/bin/ruby list_nic.rb lo0 => {} rge0 => {:inet=>"192.168.223.20", :broadcast=>"192.168.223.255", :netmask=>"255.255.255.0"} rge1 => {:inet=>"192.168.224.20", :broadcast=>"192.168.224.255", :netmask=>"255.255.255.0"}