Akash Panchal
Akash Panchal

Reputation: 305

How to take IP range from console and make requests to all IPs within range using Ruby?

I want to take IP range like 192.168.1.10-40 from console and want to make request to each IP and print responses on console.

Is this possible to do this using net/http and uri or one needs something else?

Upvotes: 1

Views: 358

Answers (3)

Jonas Elfström
Jonas Elfström

Reputation: 31428

By making a few assumptions of the syntax of your IP-ranges I ended up with the following. You might want to consider taking two full IP-addresses or CIDR instead.

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

Upvotes: 2

p0deje
p0deje

Reputation: 4063

Addition to steenslag answer.

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: added http://

Upvotes: 0

steenslag
steenslag

Reputation: 80065

The IPAddr class includes Comparable, so you can do things like:

require 'ipaddr'
(IPAddr.new("192.168.1.10")..IPAddr.new("192.168.1.40")).each{|ip| puts ip}

Upvotes: 0

Related Questions