How to check amount of data available for a socket in C and Linux

view story

http://stackoverflow.com – 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? (HowTos)