Skip to content

Instantly share code, notes, and snippets.

@kazuho
Created April 7, 2015 00:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kazuho/e614ca99ab6699c37346 to your computer and use it in GitHub Desktop.
Save kazuho/e614ca99ab6699c37346 to your computer and use it in GitHub Desktop.
use strict;
use warnings;
use IO::Socket::INET;
sub can_bind {
my $port = shift;
!! IO::Socket::INET->new(
Listen => 5,
LocalAddr => '127.0.0.1',
LocalPort => $port,
Proto => 'tcp',
ReuseAddr => 1,
);
}
sub empty_port {
for (my $port = 49152; ; ++$port) {
if (can_bind($port)) {
warn "found empty_port: $port, the socket should have been closed now that we are out of can_bind";
return $port;
}
}
}
my $s = IO::Socket::INET->new(
Listen => 5,
LocalAddr => '127.0.0.1',
LocalPort => empty_port(),
Proto => 'tcp',
ReuseAddr => 1,
) or die "could not bind to the returned port:$!";
print "ok\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment