title: Set a timeout for recv from socket on Windows
body: <p>Ih,
  I think my code is correct but it doesn't work :(</p>
  
  <p>To set a timeout for recv function on windows i know i must use this code:</p>
  
  <pre><code>                    DWORD timeout = 2000;
  
                   if (setsockopt(listenSocket, SOL_SOCKET, SO_RCVTIMEO, (char*)&amp;timeout, sizeof(DWORD)))
                   { perror("setsockopt");
                  return -1;
                   }
  </code></pre>
  
  <p>But it doesn't work.</p>
  
  <p>The code of my server is:</p>
  
  <pre><code>    SOCKET listenSocket;
  SOCKET remoteSocket= INVALID_SOCKET;
  SOCKADDR_IN Server_addr;
  SOCKADDR_IN Client_addr;
  int sin_size;
  short port;
  
  int wsastartup;
  int ls_result;
  WORD wVersionRequested = 0x0202;
  WSADATA wsaData;
  
  wsastartup = WSAStartup(wVersionRequested, &amp;wsaData);
  if (wsastartup != NO_ERROR) cout &lt;&lt; "Errore WSAStartup()" &lt;&lt; endl;
  
  listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  
  port = 4000;
  Server_addr.sin_family = AF_INET;
  Server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
  
  Server_addr.sin_port = htons(port);
  
  if (bind(listenSocket,(LPSOCKADDR) &amp;Server_addr,sizeof(struct sockaddr)) &lt; 0) {
      cout &lt;&lt; "Server: error bind." &lt;&lt; endl;
  closesocket(listenSocket);
  return -1;
  }
  
  ls_result = listen(listenSocket, SOMAXCONN);
  
  sin_size = sizeof(struct sockaddr_in);
  remoteSocket = accept(listenSocket, (struct sockaddr *) &amp;Client_addr, &amp;sin_size);
  
  // SET THE TIME OUT
  DWORD timeout = 300;
  if (setsockopt(remoteSocket, SOL_SOCKET, SO_RCVTIMEO, (char*)&amp;timeout, sizeof(DWORD)))
  { perror("setsockopt");
      return -1;
  }
  
  int i=0;
  while (i&lt;50){
      t_start = clock();
  
      // when client receives the send below it wait 3 seconds and then trasmits the answer
      send(remoteSocket, "code of start transmission", sizeof("code of start transmission"), 0);
  
      recv_size=recv(remoteSocket, messaggio, sizeof(messaggio), 0);
  
      printf("time for read=  %f second \n", ((double)(end - t_start)) / CLOCKS_PER_SEC);
  
      i=i+1;
  }
  </code></pre>
  
  <p>The client when receives the message "code of start transmission" from servers, it wait 3 seconds and then aswer to server.
  I expect time for read is 300 ms and recv_size&lt;0, instead recv_size&lt;0 but time for read is more or less 1.5 seconds (The server waits for the client's message). I don't understand why. </p>
  
  <p>I'm on windows and i'm using eclipse and mingw-w64.</p>
  
  <p>Please someone can help me??</p>