Created
July 8, 2017 23:52
-
-
Save picatz/0976371ede33c7c00d4570eac5a40869 to your computer and use it in GitHub Desktop.
Thread Pool'd connect_to method
This file contains hidden or 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
# 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