Perl: how to portably reserve a TCP port (so there will be a non-available URL) Perl: how to portably reserve a TCP port (so there will be a non-available URL) windows windows

Perl: how to portably reserve a TCP port (so there will be a non-available URL)


You should be able to bind to the loopback address using port 0 (so that a port will be allocated to you). For bonus points you may want to try to connect the socket to itself (probably not needed anywhere, but should guarantee that it has an address)


You want to bind the socket to an address+port. This which will happen if you specify a LocalAddr (or LocalHost). If you don't specify a port (or you specify port zero), a free port will be picked for you.

use strict;use warnings;use 5.010;use IO::Socket::INET qw( INADDR_ANY );my $sock = IO::Socket::INET->new(    Proto     => 'tcp',    LocalAddr => INADDR_ANY,);my $port = $sock->sockport();say $port;  # 60110

I think you want to only accept connections from the loopback adapter. If so, use INADDR_LOOPBACK instead of INADDR_ANY.


Try this small tool https://github.com/yegor256/random-tcp-port (I'm a developer). Should work in Windows, since it's ANSI C.