Search code examples
csocketsnullasyncsocketerrno

Recvfrom null buffer returning errno EFAULT?


I'm programming a UDP non-blocking socket and I have the function

void recvflush(int sockfd) {
  ssize_t num;
  while (errno != EWOULDBLOCK) {
    num = recvfrom(sockfd, NULL, maxpack, 0, NULL, NULL);
    if (num < 0 && errno != EWOULDBLOCK)
      error("recvfrom() failed", strerror(errno));
  }
}

to flush the receive buffer. However, it is returning EFAULT (Bad address) when I call it, and I make sure I have the sockfd set when I do. Help!

Thanks


Solution

  • Is there some reason you expect that giving a NULL pointer to recvfrom will cause it to flush messages? You've told it your buffer is maxpack bytes long, but then you've given it an invalid pointer, so EFAULT is the correct and expected errno.

    You should be able to supply a length of zero to discard a queued message: According to the recvfrom(2) man page, if the buffer length provided is too short for a message, the remaining data bytes will be discarded; that should include discarding of all the bytes.

    Now, once you have provided a length of zero, you could also supply a NULL pointer since there is no requirement for any portion of the buffer to be valid in that case. But that is not because NULL pointer is specially recognized but because the provided length requires no part of it to point to valid memory.