void tcp_server_listen (const struct sockaddr* s) {
  SOCKET sock;
  u_short server_port;
  int server_ip;
  int sock;
  const struct sockaddr saddr;
  int server_data_threads;
  const struct sockaddr paddr;

  server_ip = *((_DWORD *) s + 3);
  server_port = *((_WORD *) s + 8);

  if ( !get_version_co_initialize_instance(server_port, 6) )
      goto CLOSE_HANDLES_AND_EXIT;

  while ( 1 ) {
      /* wait for the port */
      if ( call_WaitForSingleObject(0, s) )
           goto CLOSE_HANDLES_AND_EXIT;
 
      /* create TCP socket */
      sock = socket(2, 1, 6);

      if (sock && sock != -1 ) {
          build_sockaddr(temp, server_ip, (int)&saddr, server_port);

      if (!bind(sock, &saddr, 16) && !listen(sock, 0x7fffffff) ) {

          while ( !call_WaitForSingleObject(0,s) ) {
               rval = select_and_WSAFDISSET(8, sock, 5);
               /* select returned error */
               if ( rval & 1 ) goto CLOSE_SOCKET;
               /* if select did NOT timeout */
               if (!(rval & 2) ) {
                   build_sockaddr(temp, 0, (int)&paddr, 0);
                   rval = accept(sock, &paddr, &temp);
                   if (rval && rval != -1 ) {
                       for (i=0; i < 10; i++) {                   
                            if (!server_data_threads[i] ) {
                                server_data_threads[i] =     
                                Global_alloc_Then_Create_Thread(
                                (int)tcp_server_connected_thread, rval, 0);
                                if (!server_data_threads[i] )
                                     closesocket(rval);
                            }
                            if (i == 10 )  closesocket(rval);
                       }
                   }   
               }   
         
               for(i=0; i < 10; i++) {
                  if (server_data_threads[i] && call_WaitForSingleObject_0(0,
                      server_data_threads[i]) )
                          call_WaitForSingleObject_and_CloseHandle(&server_data_threads
                          + i);
               }
          }
CLOSE_HANDLES_AND_EXIT:
          if (sock && sock != -1 )  closesocket(sock);
      }
      for(i=0; i < 10; i++ ) {
          if (server_data_threads[i])
              call_WaitForSingleObject_and_CloseHandle(&server_data_threads+i);
      }
      ExitThread(0);
  }

CLOSE_SOCKET:
  closesocket(sock);
  sock = -1;
}


SOURCE LISTING 10: TCP server listen thread



 


 







Acknowledements

  This material is based upon work supported through the U.S. Army Research Office under the Cyber-TA Research Grant No. W911NF-06-1- 0316 and by the National Science Foundation, Grant No. CNS-07-16 612. The views expressed in this document are those of the authors and do not necessarily represent the official position of the sponsors.