2012-02-28 68 views
4

我有6个设备配置在IP地址1到255范围192.168.1.X(其中X = 1到255)。我已经编写了这个程序来ping通并查看可用的IP地址来执行操作。但它需要很长时间来执行... 任何人都可以提出一个快速的方法来执行此操作?从255的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 
+2

'-c'不是'timeout',而是'count'。要使用超时使用'-W'和/或'-w'。您也可以通过在单独的线程中运行每个ping来加速这种情况,在这种情况下,您将在单次超时而不是255 *超时后收到所有响应。 – 2012-02-28 17:40:34

+1

或使用'nmap -sn 192.168.1.0/24' ping扫描:) – 2012-02-28 19:28:44

回答

2

测试用红宝石1.9.3定时不坏;

[[email protected] ~]$ 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 
+1

[子进程](https://gist.github.com/1944010)在同一台机器上的实现速度更快。 – 2012-02-29 20:04:13

相关问题