Let's Write a Port Scanner in Perl!

A little while back (about a month ago), I decided to write a simple port scanner in Perl so I could check out what's going on in the world of sockets programming.  I had done something similar before.  Maybe after posting this, I'll get some ideas and expand it.  I know there are ways to improve my code!

#Simple Port Scanner  
## By Greg Thompson
use strict;  
use Socket;  
use warnings;  
use 5.01;

my ($remote, $port, $iaddr, $paddr, $proto,  
                    $i, $conn, $start, $stop);

if(@ARGV < 3)  
{
    print "nsyntax: pscan address start_port end_portn";
    print "tExample: pscan google.com 79 85n";
    printf("a");
    exit;
}

chomp($remote = $ARGV[0]);  
$start = $ARGV[1];
$stop = $ARGV[2];

$iaddr = inet_aton($remote) || die "No host: $remote";
$proto = getprotobyname("tcp");

socket(SOCK, PF_INET, SOCK_STREAM, $proto) || die "socket: $!";  
print "-----Init Transmissionn";

for($i = $start;$i <= $stop;$i++)  
{
    $paddr = sockaddr_in($i, $iaddr);

    if (connect(SOCK, $paddr)){ 
        print "$remote: $i is open.n" 
    }
    elsif(!connect(SOCK, $paddr)){ 
        print "$remote: $i is closed.n" 
    }
    else{
        print "Error.n";
    }
}
print "-----End Transmissionn";

Alright, so it's not the most advanced program in the world, but it's pretty cool!  Maybe I can write something to imitate some of the features in NMap later on!

Greg

Software Engineer

Subscribe to GregBlogs