Skip to content

Instantly share code, notes, and snippets.

@seven1m
Created August 28, 2009 16:11
Show Gist options
  • Save seven1m/177072 to your computer and use it in GitHub Desktop.
Save seven1m/177072 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
# multithreaded script that probes a subnet for used/unused ip addresses
# command line usage:
#
# ./probe_ips.rb [options] [subnet]
#
# subnet defaults to 192.168.1
# -u lists used ips rather than unused
#
# should work on Mac, Linux, and Windows
class IPProber
WAIT = 3 # seconds
MAX_THREADS = 50
def initialize(subnet)
@subnet = subnet
@available = []
@used = []
@threads = []
end
def probe
(1..254).each do |index|
ip = @subnet + index.to_s
print ip + " \r"; $stdout.flush
@threads << Thread.new do
if (result = `ping -#{RUBY_PLATFORM =~ /mswin/i ? 'n' : 'c'} 1 -#{RUBY_PLATFORM =~ /darwin|mswin/i ? 'i' : 'w'} #{WAIT} #{ip}`) =~ /100% (packet )?loss/
@available << ip
else
@used << ip
end
end
if @threads.length >= MAX_THREADS
@threads.shift.join
end
end
@threads.each { |t| t.join }
puts # clear line on console
end
def available
@available.sort_by { |ip| ip.split('.').last.to_i }
end
def used
@used.sort_by { |ip| ip.split('.').last.to_i }
end
def all
(@available + @used).sort_by { |ip| ip.split('.').last.to_i }
end
end
if $0 == __FILE__
puts "probing ips..."
used = ARGV.delete('-u') || ARGV.delete('--used')
subnet = ARGV.first.dup rescue '192.168.1'
subnet << '.' unless subnet =~ /\.$/
prober = IPProber.new(subnet)
prober.probe
if used
puts 'Used IPs:'
puts prober.used
puts "#{prober.used.length}/#{prober.all.length}"
else
puts 'Available IPs:'
puts prober.available
puts "#{prober.available.length}/#{prober.all.length}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment