#!/usr/bin/env ruby -w ## # A module for retrieving IP adresses from ifconfig (tested on FreeBSD) module GetIP IFCONFIG_IP4_RE = /inet ([^\s]+) netmask ([^\s]+) broadcast ([^\s]+)/ IFCONFIG_IP6_RE = /inet6 ([^\s]+) prefixlen ([^\s]+) scopeid ([^\s]+)/ IFCONFIG_IP6_LINK_RE = /inet6 (fe80[^\s]+) prefixlen ([^\s]+) scopeid ([^\s]+)/ ## # Retrieve the ipv4 addr, netmask, and broadcast addr for +interface+ def self.ip4_addr_for(interface) `ifconfig #{interface}` =~ IFCONFIG_IP4_RE return [$1, $2, $3] end ## # Retrieve the ip6 link-level addr, prefixlength, and scope id for # +interface+ def self.ip6_link_for(interface) `ifconfig #{interface}` =~ IFCONFIG_IP6_LINK_RE return [$1, $2, $3] end ## # Retrieve all ipv6 addrs for +interface+, in addr, prefixlength, scope id # format. def self.ip6_addrs_for(interface) addrs = [] `ifconfig #{interface}`.gsub(IFCONFIG_IP6_RE) { addrs << [$1, $2, $3] } return addrs end end if $0 == __FILE__ addr = ARGV.shift unless addr then puts "usage: #{$0} interface" exit end printf("#{addr} has IPv4 address: %s\n\tnetmask %s\n\tand broadcasts on %s\n", *GetIP.ip4_addr_for(addr)) if ip6_addrs = GetIP.ip6_addrs_for(addr) then puts "#{addr} has ip6 addrs:" ip6_addrs.each do |ip6addr, prefix, scopeid| puts "\taddr: #{ip6addr}, prefix length: #{prefix}, scopeid #{scopeid}" end end end