title: C++ check TCP port
body: <p>I have written a program in <code>C++</code> and i need to check if a TCP port is truely empty. </p>
  
  <p>This is the function :</p>
  
  <pre><code>int checkport(char* host, char* port, int timeout)
  {
      int sock;
      struct sockaddr_in sin;
      int result = 0;
  
      sock = socket(AF_INET, SOCK_STREAM, 0);
  
      sin.sin_family = AF_INET;
      sin.sin_port = htons(atoi(port));
      sin.sin_addr.s_addr = inet_addr(host);
      fd_set fdset;
      struct timeval tv;
      fcntl(sock, F_SETFL, O_NONBLOCK);
  
      int connect_result = connect(sock,(struct sockaddr*)(&amp;sin),sizeof(struct sockaddr_in));
      FD_ZERO(&amp;fdset);
      FD_SET(sock, &amp;fdset);
      tv.tv_sec = timeout;
      tv.tv_usec = 0;
  
      int select_result = select(sock + 1, NULL, &amp;fdset, NULL, &amp;tv);
  
      // printf("connect = [%d] | select = [%d]\n",connect_result,select_result);
  
      if(select_result == 1)
      {
          int so_error;
          socklen_t len = sizeof so_error;
          getsockopt(sock, SOL_SOCKET, SO_ERROR, &amp;so_error, &amp;len);
  
          // printf("so_error = [%d] \n",so_error);
  
          if(so_error == 0)
          {
              //Is connected
              if(hitdebug &gt;= 4) puts("CONNECTED");
              if(hitdebug &gt;= 2) printf("[%s:%s] OPEN\n",host,port);
  
              result = 1;
          }
          else
          {
              if(hitdebug &gt;= 4) puts("CONNECT_ERROR_1");
  
              result = 0;
  
          }
      }
      else
      {
          if(hitdebug &gt;= 4) puts("CONNECT_ERROR_2");
  
          result = 0;
      }
  
      close(sock);
  
      return result;
  }
  </code></pre>
  
  <p>The problem is that is detecting only LISTEN port, i want a port to be 100% true and even detect ESTABLISHED, TIME_WAIT, etc ...</p>
  
  <p>Output :</p>
  
  <pre><code>connect = [-1] | select = [1]
  so_error = [111]
  50983 TEST=[0]
  tcp        0      0 1.2.3.4:50983       4.4.4.4:22       ESTABLISHED
  
  
  connect = [-1] | select = [1]
  so_error = [111]
  43343 TEST=[0]
  tcp        0      0 1.2.3.4:43343       4.4.4.4:22       ESTABLISHED
  
  
  connect = [-1] | select = [1]
  so_error = [0]
  64000 TEST=[1]
  tcp        0      0 1.2.3.4:64000       0.0.0.0:*               LISTEN
  tcp        0      0 1.2.3.4:47669       1.2.3.4:64000       TIME_WAIT
  
  
  connect = [-1] | select = [1]
  so_error = [111]
  54674 TEST=[0]
  
  
  connect = [-1] | select = [1]
  so_error = [111]
  54665 TEST=[0]
  </code></pre>
  
  <p>For me an empty port is when i do a <code>netstat -an | grep 12345 | wc -l</code> and i see 0, not even a FIN_WAIT</p>
  
  <p>How can i accomplish that?</p>
  
  <p>Thank you.</p>