Binding to the next available TCP port in perl

If you need to bind to lots of local ports in sequence on *nix, you can use the following perl code:

use strict;
use Socket;
use IO::Socket::INET;
my $server = IO::Socket::INET->new(Listen => 1, LocalAddr => 'localhost', LocalPort => 0, Proto => 'tcp', ReuseAddr => 1);  #use automatic port here
if($server) {    #created socket ok
   my $sockAddr = getsockname($socket);
   my($port, undef) = sockaddr_in($sockAddr);  #get the port number that linux gave us
   print "server bound to port: $port\\n";
}
else{
   die("FATAL: could not setup socket: $!");
}

linux/unix will automatically give you an unassigned port, all you have to do is read back what the OS gave you.

Last updated: 06/04/2006