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

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

Posted by: admin November 29, 2017 Leave a comment

Questions:

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?

Answers:

Yes:

#include <sys/ioctl.h>

...

int count;
ioctl(fd, FIONREAD, &count);

Questions:
Answers:

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.

Questions:
Answers:

You have to try send and receive command as well as you are able to read and write in socket character by character so no wastage of memory and even better communication.

Questions:
Answers:

You could use Non-bloking sockets, or select()/poll() for that matter. I prefer non-blocking sockets because I can do other things while waiting for new data.

Questions:
Answers:

This is a “sort of” answer: recv(char* buffer, size_t nytes, int flags) where flags is OR’ed with:

MSG_PEEK
This flag causes the receive operation to return data from the beginning of the receive queue without removing that data from the queue. Thus, a subsequent receive call will return the same data.

Such that you can see if an arbitrary number of bytes exists in the buffer, without irreversibly reading the buffer. This is a half-answer because it is not the most efficient way to do this, and MSG_PEEK is usually employed when messages have known length headers maybe like this:

000123DT001    

where 00123 is the length of the whole message including header, DT is the type of message, and 001 is the number of retries by the sender. The idea is that you can fetch something that tells you how many bytes make a complete read of a message. You are not interested in messages. But that is the reason behind MSG_PEEK

Questions:
Answers:

i think you are trying to get many packets with single system call to reduce the overhead due to system calls.

so u can try PACKET sockets interfaces for linux 2.4 or 2.6+ kernels try this http://lxr.free-electrons.com/source/Documentation/networking/packet_mmap.txt