If you find yourself writing the same code more than once, especially if your variable names start including numbers, it's time to write a common sub and refactor your code. Consider the following rework of the major portion of your code:
#!/usr/bin/perl
use warnings;
use strict;
use threads;
use IO::Socket::INET qw();
use NET::Ping qw();
use Time::HiRes qw();
my $kHost = '127.0.0.1';
my @ports = (80, 443, 53);
for my $port (@ports) {
my $SockTest = IO::Socket::INET->new(
PeerAddr => $kHost,
PeerPort => $port,
Proto => 'tcp'
) or next;
print "tcp Socket $kHost:$port opened\n";
close ($SockTest);
}
# pings a plenty
for my $mode ('icmp', 'tcp') {
my @threads = map {
threads->new(sub {doPing($kHost, $_ * 20, $mode)})
} 0 .. 4;
for my $thread (@threads) {
Time::HiRes::usleep (500_000);
$thread->join();
}
print "Done $mode test\n";
}
print "Done\n";
sub doPing {
my ($host, $portBase, $mode) = @_;
for my $port ($portBase .. $portBase + 19) {
my $ping = Net::Ping->new($mode);
$ping->port_number($port);
print "$mode ping reply on port $port\n" if $ping->ping($host)
+;
}
}
Prints (with a chunk omitted):
tcp Socket 127.0.0.1:80 opened
tcp Socket 127.0.0.1:443 opened
icmp ping reply on port 0
icmp ping reply on port 20
icmp ping reply on port 21
icmp ping reply on port 1
icmp ping reply on port 2
icmp ping reply on port 22
icmp ping reply on port 23
...
icmp ping reply on port 96
icmp ping reply on port 97
icmp ping reply on port 98
icmp ping reply on port 99
Done icmp test
tcp ping reply on port 80
Done tcp test
Done
There are a few issues with your code aside from general bad coding such as declaring all your variables up front, using C for loops and cut and pasting large swathes of code. or die "" and goto Next; isn't going to do whatever it is you expect it to because the program will exit when it hits the die without executing the goto.
sleep sleeps for integer seconds so sleep 0.5 is the same as sleep 0.
$Status is essentially useless because it is written to in multiple places (including from threads) but its value is only shown in one place where it is unaffected by any changes made in the treads in any case.
True laziness is hard work
|