Subject: | TCP/UDP version of Net::EmptyPort::empty_port |
Sorry, I know I pushed this in an earlier ticket, but I've already
written a version of this based on your existing code. Here's a drop-in
replacement for the empty_port sub that is completely compatible with
the existing versions:
sub empty_port {
my $port = do {
if (@_) {
my $p = $_[0];
$p = 49152 unless $p =~ /^[0-9]+$/ && $p < 49152;
$p;
} else {
50000 + int(rand()*1000);
}
};
my $proto = $_[1] ? lc($_[1]) : 'tcp';
while ( $port++ < 60000 ) {
next if ($proto eq 'tcp' && check_port($port)); # UDP is
connectionless
my $sock = IO::Socket::INET->new(
(($proto eq 'udp') ? () : (Listen => 5)),
LocalAddr => '127.0.0.1',
LocalPort => $port,
Proto => $proto,
(($^O eq 'MSWin32') ? () : (ReuseAddr => 1)),
);
return $port if $sock;
}
die "empty port not found";
}
So, empty_port(5963, 'udp') will look for a UDP port and make sure that
it's not already taken by the PC/server. The existing one-param syntax
will default to TCP. Replacing check_port and wait_port isn't needed,
because they wouldn't work for UDP.
I thought about putting this in as another module, but the 4 line change
to the existing function seems too trivial to warrant a separate fork.