Determining the number of bytes ready for recv () 'd

I can use select () to determine if the recv () call will block, but as soon as I determine that it is their bytes to read, this is their way of asking how many bytes are currently available before I actually call recv ()?

+1
source share
2 answers

If your OS provides it (and most of them), you can use ioctl (.., FIONREAD, ..):

int get_n_readable_bytes(int fd) {
    int n = -1;
    if (ioctl(fd, FIONREAD, &n) < 0) {
        perror("ioctl failed");
        return -1;
    }
    return n;
}

Windows provides a similar ioctlsocket (.., FIONREAD, ..), which expects the pointer to be unsigned long:

unsigned long get_n_readable_bytes(SOCKET sock) {
    unsigned long n = -1;
   if (ioctlsocket(sock, FIONREAD, &n) < 0) {
       /* look in WSAGetLastError() for the error code */
       return 0;
   }
   return n;
}

ioctl โ€‹โ€‹ fds, fds. , TCP unix- , , , . UDP: .

ioctlsocket Windows () .

+3

, . :

  • , , X .
  • , X .
  • , /.
+2

All Articles