Subscribed unsubscribe Subscribe Subscribe

Kentaro Kuribayashi's blog

Software Engineering, Management, Books, and Daily Journal.

How to get an arbitrary empty port

Sometimes we want an arbitrary empty port when testing a server program. The code below works for that case.

#!/usr/bin/env perl
use v5.14;
use IO::Socket::INET;

sub empty_port () {
    my $sock = IO::Socket::INET->new(
        Prot   => 'tcp',
        Listen => 1,
        (($^O eq 'MSWin32') ? () : (ReuseAddr => 1)),
    );
    my $port = $sock->sockport;
    $sock->close;
    $port;
}

say empty_port;

But the code can violate RFC2750 which says:

Following the policies outlined in [IANA-CONSIDERATIONS], numbers 0-49151 are allocated as standard policy elements by IETF Consensus action, numbers in the range 49152-53247 are allocated as vendor specific (one per vendor) by First Come First Serve, and numbers 53248-65535 are reserved for private use and are not assigned by IANA.

http://tools.ietf.org/html/rfc2750

Conclusion: just use Test::TCP#empty_port();