我想从控制台获取类似192.168.1.10-40的IP范围,并希望向每个IP发出请求并在控制台上打印响应。
使用net / http和uri还是需要别的东西可以做到这一点吗?
答案 0 :(得分:2)
通过对IP范围的语法做一些假设,我得到了以下结论。您可能需要考虑使用两个完整的IP地址或CIDR。
require 'ipaddr'
require 'net/http'
require 'uri'
range = ARGV[0]
from, part = range.split("-")
arr_from, arr_part = from.split("."), part.split(".")
to = (arr_from.take(4-arr_part.length) << arr_part).join(".")
puts "HTTP responses from #{from} to #{to}"
ip_from = IPAddr.new(from)
ip_to = IPAddr.new(to)
(ip_from..ip_to).each do |ip|
puts ip.to_s
begin
puts Net::HTTP.get( URI.parse("http://#{ip.to_s}/") )
rescue => e
puts e.message
end
end
答案 1 :(得分:0)
IPAddr类包含Comparable,因此您可以执行以下操作:
require 'ipaddr'
(IPAddr.new("192.168.1.10")..IPAddr.new("192.168.1.40")).each{|ip| puts ip}
答案 2 :(得分:0)
除了steenslag回答。
require 'net/http'
require 'uri'
require 'ipaddr'
(IPAddr.new("192.168.1.10")..IPAddr.new("192.168.1.40")).each do |address|
puts Net::HTTP.get(URI.parse("http://#{address.to_s}"))
end
UPD:已添加http://