I was wondering whether gnulib has a function to safely read or recv
from a file desctiptor. I could not find one, and have had to hack
them up on numerous occasions. Here is one such version I wrote while
implementing a feature for GNU Inetutils:
size_t
recvbuf (int sockfd, void **buffer, size_t *size)
{
  size_t count = 0;
  size_t nread;

  if (*buffer == NULL)
    *size = BUFSIZ;

  for (;;)
    {
      *buffer = realloc (*buffer, *size);
      nread = recv (sockfd, *buffer + count, BUFSIZ, 0);

      if (nread == -1)
        error (EXIT_FAILURE, errno, "recv");

      count += nread;

      if (nread < BUFSIZ)
        break;
      else
        *size += BUFSIZ;
    }

  return count;
}

Comments?

Happy hacking,
Debarshi


Reply via email to