Ever wondered how to find out how many bytes can be read from a socket? I did and it is really simple although possibly not portable.
ssize_t socket_get_available(int socket_fd)
{
int available = -1;
assert(0 <= socket_fd);
if (ioctl(socket_fd, FIONREAD, &available) < 0) {
return -1;
}
return (ssize_t) available;
}