Last active
August 29, 2015 14:01
-
-
Save rye/f9288aa9c5eaba67e57f to your computer and use it in GitHub Desktop.
A small ruby module for determining if ports are open.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'socket' | |
require 'timeout' | |
module Porto | |
class PortoPort | |
def self.in_use?(ip, port) | |
begin | |
Timeout::timeout(1) do | |
begin | |
s = TCPSocket.new(ip, port) | |
s.close | |
return true | |
rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH | |
return false | |
end | |
end | |
rescue Timeout::Error | |
end | |
return false | |
end | |
def self.free?(ip, port) | |
!self.in_use?(ip, port) | |
end | |
end | |
def self.scan(range, silent = false) | |
raise ArgumentError, "`range' argument must be of class Range" unless range.class == Range | |
reports = [] | |
range.each do |port| | |
print "." unless silent | |
reports << { | |
port: port, | |
free: (Porto::PortoPort.free? 'localhost', port) | |
} | |
end | |
puts unless silent | |
reports | |
end | |
end | |
Porto::scan((0..25565)).select{|x| !x[:free]}.each do |port| | |
puts "Port: #{port[:port]}" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment