Module: Pingfacts

Defined in:
lib/pingfacts.rb,
lib/pingfacts/version.rb

Defined Under Namespace

Classes: Error, PingerResult

Constant Summary collapse

VERSION =
"0.1.4"

Class Method Summary collapse

Class Method Details

.scan(network_args, method = Net::Ping::External) ⇒ Object



114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
# File 'lib/pingfacts.rb', line 114

def self.scan(network_args, method=Net::Ping::External)
  network_list = []
  pingers = []
  onlines = []

  if network_args.class == Array
    network_list += network_args
  else
    network_list << network_args
  end

  network_list.each do |network|
    begin
      ip_range = IPAddr.new(network).to_range

      ip_range.each do |ip|
        pingers << Thread.new do
          pinger = Net::Ping::External.new(ip.to_s)
          if pinger.ping?
            onlines << ip.to_s
          end
        end
      end
    rescue IPAddr::InvalidAddressError
      pingers << Thread.new do
        pinger = Net::Ping::External.new(network)
        if pinger.ping?
          onlines << network
        end
      end
    end
  end

  pingers.each do |t|
    t.join
  end

  mac_addresses = {}
  begin
    `ip neigh`.lines.each do |line|
      r = line.split(/\s+/)
      if r[3] == "lladdr"
        mac_addresses[r[0].strip] = r[4].strip
      end
    end
  rescue
    nil
  end

  result = []

  onlines.each do |ip|
    ipresult = PingerResult.new
    ipresult.ip = ip
    if mac_addresses.key?(ip)
      ipresult.mac = mac_addresses[ip]
    end
    begin
      ipresult.dnsname = Resolv.getname(ip)
    rescue Resolv::ResolvError
      ipresult.ip = Resolv.getaddress(ip)
      ipresult.dnsname = ip
    rescue
      nil
    end

    result << ipresult
  end

  result
end