If using socket
Bind to port zero. The system will pick an unused port. You can find out the number of the port to which the socket was bound as follows:
use Socket qw( sockaddr_in ); my $port = (sockaddr_in(getsockname(SOCK)))[0]; print("Listening to port $port.\n");
If using IO::Socket/IO::Socket::INET
Don't specify a LocalPort or use LocalPort => 0. The system will pick an unused port. You can find out the number of the port to which the socket was bound as follows:
my $port = $sock->sockport(); print("Listening to port $port.\n");
Update: Added IO::Socket method.
In reply to Re: What's the best way to find an unused TCP port on the local system
by ikegami
in thread What's the best way to find an unused TCP port on the local system
by DrWhy
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |