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) {
return 0;
}
return n;
}
ioctl โโ fds, fds. , TCP unix- , , , . UDP: .
ioctlsocket Windows () .