Skip to content

Instantly share code, notes, and snippets.

@picatz
Last active June 21, 2019 14:41
Show Gist options
  • Save picatz/63d77fb2fde04508e75a2e3912384382 to your computer and use it in GitHub Desktop.
Save picatz/63d77fb2fde04508e75a2e3912384382 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'async/io'
require 'async/semaphore'
def scan_port(host, port, timeout)
Async do |task|
task.with_timeout(timeout) do
address = Async::IO::Address.tcp(host, port)
Async::IO::Socket.connect(address).close
puts "#{port} open"
rescue Errno::ECONNREFUSED
puts "#{port} closed"
rescue Async::TimeoutError
puts "#{port} timeout"
end
end
end
Async do
host = "localhost"
ports = Range.new(1, 8080)
timeout = 1.0
limits = Process.getrlimit(Process::RLIMIT_NOFILE)
batch_size = [512, (limits.first * 0.9).ceil].min
semaphore = Async::Semaphore.new(batch_size)
ports.each do |port|
semaphore.async do
scan_port(host, port, timeout)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment