Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

linux

sockets

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?

like image 603
Jimm Avatar asked Dec 27 '12 00:12

Jimm


People also ask

What are sockets in C?

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.


2 Answers

Yes:

#include <sys/ioctl.h>  ...  int count; ioctl(fd, FIONREAD, &count); 
like image 132
fizzer Avatar answered Oct 05 '22 11:10

fizzer


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.

like image 24
Greg Hewgill Avatar answered Oct 05 '22 11:10

Greg Hewgill