title: How to use sockets recv(,,,) for an indeterminate response length
body: <p>I have a requirement to send commands and read responses from a device using IrDA sockets communication.  Although packaging up the commands is fairly straight forward, determining the expected size of the response is not possible. For example the command "GET_ERRORS" results in the device returning data from <em>0 to n</em>,  <code>\n</code> delimited lines of up to 80 bytes each.  I have read the post <strong>*<a href="https://stackoverflow.com/a/7782422/645128">here</a>, but the ***header preceding the actual data block*</strong> is not provided to me by the device.  </p>
  
  <p>[EDIT]<br>
  Here is a typical response from the GET_ERRORS command (shorted for readability):  </p>
  
  <pre><code>Date       Time     Fault
  10/12/2000 02:00:00 3f46
  10/12/2000 02:00:00 bcf5
  10/12/2000 02:00:00 1312
  10/12/2000 02:00:00 a334
  10/12/2000 02:00:00 b212
  10/12/2000 02:00:00 b212
  10/12/2000 02:00:00 c43a
  %
  </code></pre>
  
  <p>This example, (from a SO post <strong><em><a href="https://stackoverflow.com/a/12696176/645128">HERE</a></em></strong>) works well if I know the length of data being returned: </p>
  
  <pre><code>int recv_all(int sockfd, void *buf, size_t len, int flags)
  {
      size_t toread = len;
      char  *bufptr = (char*) buf;
  
      while (toread &gt; 0)
      {
          ssize_t rsz = recv(sockfd, bufptr, toread, flags);
          if (rsz &lt;= 0)
              return rsz;  /* Error or other end closed cnnection */
  
          toread -= rsz;  /* Read less next time */
          bufptr += rsz;  /* Next buffer position to read into */
      }
  
      return len;
  }
  </code></pre>
  
  <p>But if I want to receive an unknown amount of data, the only thing I know to do is to declare a large buffer, then pass it to something like this:</p>
  
  <pre><code>int IrdaCommReceive(int irdaCommSocket, void* largeBuf, size_t len, int* rcvd)
  {
      char *bufptr = (char *)largeBuf;
  
      int bytesRcvd = recv(irdaCommSocket, bufptr, len, 0);
  
      if (bytesRcvd &lt; 0) return WSAGetLastError();
      *rcvd = bytesRcvd;
  
      return 0;
  }
  </code></pre>
  
  <p>Is there a better way to write a receive function for sockets data of an indeterminate size? </p>