#include <sys/types.h>
#include <sys/time.h>

int receive_using_select(sock, buffer, length)
int sock, length;
char *buffer;
{
  int received, status;
  fd_set fdset;
  struct timeval timeout;

  FD_ZERO(&fdset); FD_SET(sock, &fdset);

  timeout.tv_sec = 0; timeout.tv_usec = 30000;	/* wait 30000 microseconds */

  /* Check if data is available.  Note that the select()
   * system call destroys (i.e., marks) the data in
   * fdset.  For repeated calls, copy its value to a temp
   * variable.
   */
  status = select(1,  &fdset, NULL, NULL, &timeout);
  if (status == -1) {
	perror("select");
	return ERROR_IN_SELECT;
  }
  if (status == 0) return NO_DATA;

  /* Data has arrived --- read it. */
  received = recv(sock, buffer, length, 0);

  if (received == -1) {
        perror("receive");
        return ERROR_IN_DATA;
  }
  if (received == length) return 0;
  return DATA_LOST;
}
