I have a server that receives a continuous stream of data. As opposed to reading multiple times from a socket, I would like to read the entire data in socket receive buffer with one system call to read()
.
Of course I can pass a large buffer and read()
will try to fill it with all available data. But this would waste a lot of memory as most of the times the malloc'ed buffer would be bigger than actual data available on socket. Is there a way to query the available data on a socket?
A socket is a generalized interprocess communication channel. Like a pipe, a socket is represented as a file descriptor. Unlike pipes sockets support communication between unrelated processes, and even between processes running on different machines that communicate over a network.
Yes:
#include <sys/ioctl.h> ... int count; ioctl(fd, FIONREAD, &count);
No, there is not. Even if there were a way to do this, any answer you get would be immediately out of date (because new data may arrive at any time).
Note that when you pass a buffer to read()
, the function will return when there is any amount of data to read (at least one byte), instead of waiting for the buffer to completely fill.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With