title: How to Choose a Port Number?
body: <p>I'm writing a program which uses ZeroMQ to communicate with other running programs on the same machine. I want to choose a port number at run time to avoid the possibility of collisions. Here is an example of a piece of code I wrote to accomplish this.</p>
  
  
  
  <pre><code>#!/usr/bin/perl -Tw
  
  use strict;
  use warnings;
  
  my %in_use;
  {
      local $ENV{PATH} = '/bin:/usr/bin';
  
      %in_use = map { $_ =&gt; 1 } split /\n/, qx(
          netstat -aunt          |\
          awk '{print \$4}'      |\
          grep :                 |\
          awk -F: '{print \$NF}'
      );
  }
  
  my ($port) = grep { not $in_use{$_} } 50_000 .. 59_999;
  
  print "$port is available\n";
  </code></pre>
  
  <p>The procedure is:</p>
  
  <ol>
  <li><p>invoke netstat -aunt</p></li>
  <li><p>parse the result</p></li>
  <li><p>choose the first port on a fixed range which doesn't appear on netstat list.</p></li>
  </ol>
  
  <p>Is there a system utility better suited to accomplishing this?</p>