Class: IPScanner

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

Class Method Summary collapse

Class Method Details

.autodetect_new(ip_base = nil, lapse: 30, &blk) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/ipscanner.rb', line 48

def self.autodetect_new(ip_base=nil, lapse: 30, &blk)        
  
  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
  
  
  loop do
    
    sleep lapse
    a2 = scan ip_base
    found = a2 - a1
    blk.call(found) if found.any?
    a1 = a2

  end
  
end

.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



70
71
72
# File 'lib/ipscanner.rb', line 70

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

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



85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/ipscanner.rb', line 85

def self.pingecho(host, timeout=5, service="echo")
  begin
    Timeout.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



74
75
76
77
78
79
80
81
82
83
# File 'lib/ipscanner.rb', line 74

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