Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
require 'net/http'
require 'socket'
def with_unresponsive_dns
fake_dns_ip = "127.0.0.1"
th = Thread.new do
server = UDPSocket.new
server.bind(fake_dns_ip, 53)
server.recvfrom(16)
sleep
end
original_dns = %x(cat /etc/resolv.conf |grep -i '^nameserver'|head -n1|cut -d ' ' -f2).strip
`echo "$(sed 's/#{original_dns}/#{fake_dns_ip}/g' /etc/resolv.conf)" > /etc/resolv.conf`
yield
ensure
`echo "$(sed 's/#{fake_dns_ip}/#{original_dns}/g' /etc/resolv.conf)" > /etc/resolv.conf`
th.kill
th.join
end
now = Time.now
begin
with_unresponsive_dns do
uri = URI('http://example.com/some_path?query=string')
puts "beginning HTTP request. This should timeout after 1s"
Net::HTTP.start(uri.host, uri.port, open_timeout: 1)
end
ensure
puts "elapsed: #{Time.now - now}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.