Skip to content

Instantly share code, notes, and snippets.

@hakanensari
Created January 28, 2011 12:50
Show Gist options
  • Save hakanensari/800214 to your computer and use it in GitHub Desktop.
Save hakanensari/800214 to your computer and use it in GitHub Desktop.
Attach Net:HTTP requests to multiple local IPs
require 'net/http'
ips = `ifconfig | awk '/inet addr:[0-9]/{print $2;}' | grep -oE '([0-9.]{7,})'`.
split("\n").
select { |ip| ip.match(/\./) && !ip.match(/^127/) }
def attach_to(ip)
TCPSocket.instance_eval do
(class << self; self; end).instance_eval do
alias_method :original_open, :open
define_method(:open) do |conn_address, conn_port|
original_open(conn_address, conn_port, ip)
end
end
end
yield
TCPSocket.instance_eval do
(class << self; self; end).instance_eval do
alias_method :open, :original_open
remove_method :original_open
end
end
end
ips.each do |ip|
attach_to(ip) do
url = URI.parse('http://www.whatismyip.com')
begin
res = Net::HTTP.start(url.host, url.port) do |http|
http.get('/automation/n09230945.asp')
end
puts "#{ip} got response: #{res.body}"
rescue Exception => e
puts "#{ip} raised: #{e.message}"
end
end
end
@hakanensari
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment