title: Check if TCP port is available (not listening or connected)
body: <p>I use following code to check if a port is available or not:</p>
  
  <pre><code>bool ClassA::CheckPortTCP(short int dwPort , char *ipAddressStr)  
  {  
      struct sockaddr_in client;         
      int sock;   
  
      client.sin_family = AF_INET;  
      client.sin_port = htons(dwPort);  
      client.sin_addr.S_un.S_addr = inet_addr(ipAddressStr);      
  
      sock = (int) socket(AF_INET, SOCK_STREAM, 0);  
  
      int result = connect(sock, (struct sockaddr *) &amp;client,sizeof(client)); 
  
      // change to result == 0 -&gt; failure in writing code too quick ;-)
      if (result = 0) return true; // port is active and used
      else return false; 
  }  
  </code></pre>
  
  <p>The problem is if the port is opened but not connected the check failed! How can I easily examine that the port is available (not listening, not connected)?</p>
  
  <p>e.g. port 21111 (output of netstat) -> my function doesn't recognize that the port is not free</p>
  
  <pre><code>TCP    0.0.0.0:21111          xxxxDUMMYxxxx:0       LISTENING
  </code></pre>
  
  <p>Thx</p>