3
# Picks a random TCP port and attempts to bind it, retrying a few
4
# times if the chosen port is in use. This is better than just
5
# picking a random number without checking whether it is in use (but
6
# of course a race window still exists).
8
# On success, prints a port number on stdout and exits with status 0.
9
# On failure, prints an error on stderr and exits with a nonzero status.
15
socket(SOCK, PF_INET, SOCK_STREAM, 0) || die "socket: $!\n";
16
for (my ($i) = 0; ; $i++) {
17
my ($port) = int(rand(16383)) + 49152;
18
if (bind(SOCK, sockaddr_in($port, INADDR_ANY))) {
21
} elsif ($i < 10 && $!{EADDRINUSE}) {
22
# Address already in use. Try again.