title: how do I find in C that a port is free to use?
body: <p>The OS is Linux.
  I have a server process that can change its port realtime. However I would like to know in advance if a port is free before binding.</p>
  
  <p>Scenario: Server binds localhost:5000 and receives a request to bind at localhost:6000. The server has to check if the port is free. This question seeks for answers that provide a routine that checks if a port is free or not.</p>
  
  <p>For the record, I am editing my question with a code snippet that checks if a port is free to use. This does not mean that it will be used. The code below answer to the question "if the port is available right now", it does not use it. Opens a socket, check if bind returns EADDRINUSE and closes the socket.  </p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;sys/socket.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;arpa/inet.h&gt;
  #include &lt;errno.h&gt;
  
  int main(int argc, char **argv) {
  
      struct sockaddr_in serv_addr;
      if( argc &lt; 2 )
          return 0;
      int port = atoi(argv[1]);
  
      int sockfd = socket(AF_INET, SOCK_STREAM, 0);
      if( sockfd &lt; 0 ) {
          printf("socket error\n");
          return 0;
      } else {
          printf("Opened fd %d\n", sockfd);
      }
  
       bzero((char *) &amp;serv_addr, sizeof(serv_addr));
       serv_addr.sin_family = AF_INET;
       serv_addr.sin_addr.s_addr = INADDR_ANY;
       serv_addr.sin_port = htons(port);
       if (bind(sockfd, (struct sockaddr *) &amp;serv_addr, sizeof(serv_addr)) &lt; 0) {
  
          if( errno == EADDRINUSE )
          {
              printf("the port is not available. already to other process\n");
          } else {
              printf("could not bind to process (%d) %s\n", errno, strerror(errno));
          }
      }
  
      if (close (sockfd) &lt; 0 ) {
          printf("did not close fd: %s\n", strerror(errno));
          return errno;
      }
  
      return 0;
  
  
  }
  </code></pre>
  
  <p>Here are some sample runs (partial outputs)</p>
  
  <pre><code>[bash{1051}{51}]:[~/some_sources/checkbind]::./a.out 41067
  the port is not available. already to other process
  [bash{1052}{52}]:[~/some_sources/checkbind]::./a.out 22
  could not bind to process (13) Permission denied
  [bash{1053}{53}]:[~/some_sources/checkbind]::./a.out 22000
  Opened fd 3
  </code></pre>