Skip to content

Instantly share code, notes, and snippets.

@picatz
Created July 8, 2017 23:52
Show Gist options
  • Save picatz/0976371ede33c7c00d4570eac5a40869 to your computer and use it in GitHub Desktop.
Save picatz/0976371ede33c7c00d4570eac5a40869 to your computer and use it in GitHub Desktop.
Thread Pool'd connect_to method
# previous code...
class PortScanner
# previous code ...
def connect_to(port, ip = @host)
# Create proccess to be ran later.
p = Proc.new do
# Create socket.
s = Socket.new(:INET, :STREAM)
# Pack socket address.
r = Socket.sockaddr_in(port, ip)
# Try to practically process socket connection.
begin
begin
s.connect_nonblock(r)
rescue IO::EINPROGRESSWaitWritable
# Wait for handshake to complete,
# timeout after hanging 1 second.
IO.select(nil, [s], nil, 1)
begin
# Check connection failure.
s.connect_nonblock(r)
rescue => e
# If the error is "socket in use", it's open.
if e.is_a? Errno::EISCONN
@semaphore.synchronize { puts port.to_s << " Open" }
elsif
@semaphore.synchronize { puts port.to_s << " Closed" }
end
end
end
ensure
# Make sure we close that bad boy!
s.close
end
end
# Yield process to be pool'd up and call'd later.
yield p
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment