Class: IPScanner

Inherits:
Object
  • Object
show all
Defined in:
lib/ipscanner.rb

Class Method Summary collapse

Class Method Details

.detect_new(ip_base = nil) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/ipscanner.rb', line 10

def self.detect_new(ip_base=nil)
  
  ip_base = local_ip.ip_address[/\d+\.\d+\.\d+\./] unless ip_base
  
  puts "scanning the network (#{ip_base}x)"

  a1 = scan ip_base
  puts "found %d IP addresses" % a1.length
  k = :y

  while k == :y do

    print 'scan to detect new IP addresses? (y/n) '
    k = gets.lstrip.chomp.to_sym
    (puts 'enter y or n'; k = :y) if k != :y and k != :n
    
    return if k == :n
    
    a2 = scan ip_base
    found = a2 - a1
    
    if a2 == a1 then
      puts 'no new IP addresses found'
    else
      if found.any? then
        puts 'found : ' + found.inspect 
      else
        puts "found %d IP addresses" % a1.length
      end
    end
    
    a1 = a2

  end

  
end

.local_ipObject



48
49
50
# File 'lib/ipscanner.rb', line 48

def self.local_ip()
  Socket.ip_address_list.find { |ai| ai.ipv4? && !ai.ipv4_loopback? }
end

.pingecho(host, timeout = 5, service = "echo") ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/ipscanner.rb', line 63

def self.pingecho(host, timeout=5, service="echo")
  begin
    timeout(timeout) do
    s = TCPSocket.new(host, service)
    s.close
    end
  rescue Errno::ECONNREFUSED
    return true
  rescue Timeout::Error, StandardError
    return false
  end
  return true
end

.scan(ip_base = nil, range = 1..254, t = 1) ⇒ Object



52
53
54
55
56
57
58
59
60
61
# File 'lib/ipscanner.rb', line 52

def self.scan(ip_base=nil, range=1..254, t=1)
  
  ip_base = local_ip.ip_address[/\d+\.\d+\.\d+\./] unless ip_base    
  
  a = []
  (range).map{|i| Thread.new {a << i if pingecho(ip_base+i.to_s, t) }}.join
  sleep t + 0.25
  
  a.sort.map{|x| ip_base + x.to_s}
end