Hi, I've used the following two subs successfully on Win32 but they were written to be cross platform and I think they should work.
used as my $newport = get_next_free_local_port(9000); gets the next free port starting from 9000. sub local_port_is_free { my ($portnumber) = @_; my $proto = getprotobyname('tcp'); my $iaddr = inet_aton('localhost'); my $timeout = 5; my $freeport = 0; my $paddr = sockaddr_in($portnumber, $iaddr); socket(SOCKET, PF_INET, SOCK_STREAM, $proto); eval { local $SIG{ALRM} = sub { die "timeout" }; alarm($timeout); connect(SOCKET, $paddr) || error(); }; if ($@) { eval {close SOCKET; }; $freeport = $portnumber; } else { eval {close SOCKET; }; } alarm(0); return $freeport; } sub get_next_free_local_port { my ($startport) = @_; my $freeport = 0; my $tryport = $startport; while(not $freeport = local_port_is_free($tryport) ) { $tryport ++; die("Cannot find free port") if $tryport > ($startport + 100); } return $freeport; } On 01/11/2010 19:42, Edwards, Mark (CXO) wrote: > 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 > _______________________________________________ Perl-Win32-Users mailing list Perl-Win32-Users@listserv.ActiveState.com To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs