jessica1231 has asked for the wisdom of the Perl Monks concerning the following question:

Well awhile ago i made this simple perl code to check for open ports on a range of ip's.
use IO::Socket; my $in_file2 = 'rang.txt'; open DAT,$in_file2; my @ip=<DAT>; close DAT; chomp(@ip); foreach my $ip(@ip) { $host = IO::Socket::INET->new( PeerAddr => $ip, PeerPort => 80, proto => 'tcp', Timeout=> 1 ) and open(OUT, ">>port.txt"); print OUT $ip."\n"; close(OUT); }
Now it works fine.. BUT I would like it multi-threaded so i can scan quicker and larger ranges. i have tried everything but nothing has worked, either the program did not work, or i was getting duplicates of everything. any help is appreciated.

Replies are listed 'Best First'.
Re: Making a multi-threaded port scanner in perl?
by Corion (Patriarch) on Jan 13, 2014 at 08:34 UTC

    A good start to help us help you better would be to show us the code that you tried but which did not work for you.

    The general approach I would use would be to use a worker model like the following:

    1. Create a Thread::Queue, "$hosts". This is where the worker threads will get their units of work from.
    2. Read all the hosts into that queue, so the worker threads have something to do.
    3. Create another Thread::Queue, "$portstatus". This is where the worker threads will store their results.
    4. Create some worker threads, which will do mostly what your single-threaded version did:
      sub scan_host { while( my( $ip )= $hosts->dequeue() ) { warn "Scanning '$ip'"; ... do real work $portstatus->enqueue({ host => $ip, status => 'too lazy', }); }; } for( 1..$NUM_THREADS ) { threads->create( \&scan_host ); };
    5. Now, just read out the results as they come in:
      $hosts->end; while(my $result= $portstatus->dequeue()) { print Dumper $result; };

    An easier way would be to run the nmap binary and use Nmap::Parser for the results.

Re: Making a multi-threaded port scanner in perl?
by Anonymous Monk on Jan 13, 2014 at 08:30 UTC

    i have tried everything but nothing has worked, either the program did not work, or i was getting duplicates of everything. any help is appreciated.

    Great, can you show that code?

Re: Making a multi-threaded port scanner in perl?
by Preceptor (Deacon) on Jan 13, 2014 at 21:38 UTC

    Permit me to offer an example of a queue/worker. sample

    You'll want an output queue, to collate any results.