Threading methods & args

Well, this is my simple port scanner
Instead of actually Threading the scan it just prints:
“C:\Users\admin>C:\Ruby193\bin\ruby.exe
C:\Users\admin\Desktop\port-scanner.rb
choose host:”
why ?

require ‘socket’

def scanner
print "choose host: "
arg1 = gets.chomp
print "choose starting port: "
arg2 = gets.to_i
print "choose ending port: "
arg3 = gets.to_i
while arg2 <= arg3
begin
s = TCPSocket.new(arg1, arg2) # arg1 = host, arg2 = sport, arg3 =
eport
if s
puts “Port #{arg2} is open!”
end
rescue
puts “Port #{arg2} is closed!”
end
arg2 += 1

end
end

Thread.start {scanner}

Hi,

This makes no sense. What you’re doing is create a single thread at the
end of the code. How is this thread supposed to create any concurrency?
It probably won’t even run, because the main thread will exit at pretty
much the same time.

What you probably want to do is create the socket objects in separate
threads. So do it:

Thread.new do
s = TCPSocket.new …

end

But you must save the thread objects in an array and call “join” for
each of them in the main thread. This will make the main thread wait for
the socket threads to finish.

On 08/27/2012 10:05 AM, bar hofesh wrote:

eport

Thread.start {scanner}

*) You only launch one thread
*) You launch your whole program in that one thread
*) Your main thread doesn’t wait for the thread to do its work
*) You probably want to use Thread#new rather than Thread#start

This is not at all good, but works along the lines of what you are doing
here. Obviously there is a LOT of code missing.

#===============================================================================
#!/usr/bin/env ruby

require ‘socket’
require ‘logger’

def scanner
log = Logger.new(STDOUT)
print "choose host: "
host = gets.chomp
print "choose starting port: "
start_port = gets.to_i
print "choose ending port: "
end_port = gets.to_i
puts “Scanning #{host} from #{start_port} to #{end_port}”
threads = []
(start_port…end_port).each {|port|
threads << Thread.new {
begin
s = TCPSocket.new(host, port)
if s
log.info { “Port #{port} is open!” }
end
rescue
log.info { “Port #{port} is closed!” }
ensure
s.close if s
end
}
}
threads.each { |thread| thread.join }
end

scanner

#===============================================================================

Hope that helps/ gets you started =]

Sam

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs