I thought of something like that but would rather implement it using some kind 
of Perl socket routine.  I'll be using this on Windows and different flavors of 
Unix and the output format of netstat differs.

-----Original Message-----
From: perl-win32-users-boun...@listserv.activestate.com 
[mailto:perl-win32-users-boun...@listserv.activestate.com] On Behalf Of Brian 
Raven
Sent: Monday, November 01, 2010 5:07 AM
To: perl-win32-users@listserv.ActiveState.com
Subject: RE: Checking for Available Port

Edwards, Mark (CXO) <> wrote:
> I'm writing a simple port listener script using
> 
> $local=IO::Socket::INET->new(Proto=>"tcp",
>         LocalPort=>$port,
>         Listen=>1,
>         Reuse=>1,) or die "Can't open listening port: $!\n";
> 
> Everything works fine except I want to check to see if the port is
> available before I try to open it.  In some cases, if the machine is
> already listening on a port, the script dies as expected.  In other
> cases the script runs but isn't really listening.  Sometimes it takes
> over a LISTENING port.  I want to check for LISTENING or ESTABLISHED
> ports.     

Use something like `netstat -na`. For example:

sub tcp_port_state {
    my $port_to_check = shift;
    foreach (`netstat -na`) {
        next unless /tcp/i;
        my ($proto, $local, $remote, $state) = split;
        my ($ip, $port) = split /:/, $local;
        if ($port == $port_to_check) {
            return $state;
        }
    }
    return "NOT IN USE";
}

HTH

-- 
Brian Raven 
 
Please consider the environment before printing this e-mail.

This e-mail may contain confidential and/or privileged information. If you are 
not the intended recipient or have received this e-mail in error, please advise 
the sender immediately by reply e-mail and delete this message and any 
attachments without retaining a copy.

Any unauthorised copying, disclosure or distribution of the material in this 
e-mail is strictly forbidden.
_______________________________________________
Perl-Win32-Users mailing list
Perl-Win32-Users@listserv.ActiveState.com
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs
_______________________________________________
Perl-Win32-Users mailing list
Perl-Win32-Users@listserv.ActiveState.com
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs

Reply via email to