ruby – 从255个ip地址查找可用设备的方法

我在IP地址1到255上配置了6个设备,范围为192.168.1.X(其中X = 1到255).我已经编写了这个程序来ping并查看可用的IP地址来执行操作.但是执行这么长时间……

任何人都建议一个快速的方法来执行此操作?

叉子的使用也很受欢迎……

这是程序:

server = "192.168.1"
for i in (1...255)
  system("ping -q -c #{timeout} #{server}.#{i} 2&>/dev/null")
  if $?.exitstatus == 0
    # operations
  end
end

最佳答案 测试ruby1.9.3时间不错;

[slmn@uriel ~]$time ruby ipmap.rb 
"192.168.0.1"
"192.168.0.10"

real    0m2.393s
user    0m0.750s
sys     0m1.547s

如果你想做你的操作线程,我评论了这些区域;

require 'ipaddr'

ips = IPAddr.new("192.168.1.0/24").to_range

threads = ips.map do |ip|
  Thread.new do
    status = system("ping -q -W 1 -c 1 #{ip}",
                    [:err, :out] => "/dev/null")

    # you can do your operations in thread like this
    # if status
    #   # operations
    # end

    # optional
    Thread.current[:result] = ip.to_s if status
  end
end

threads.each {|t| t.join}

# if you don't do your operations in thread
threads.each do |t|
  next unless t[:result]

  # operations

  #optional
  puts t[:result]
end
点赞