Get Bytes Available on C Socket

Ever wondered how to read how many bytes are received on a socket before you decide you need to do some processing on it? It can be achieved by doing a simple ioctl(input/output control) call on the socket itself. Here is a little function I have used in the past.

long bytes_on_socket(int socket)
{
        size_t nbytes = 0;
        if ( ioctl(fd, FIONREAD, (char*)&nbytes) < 0 )  {
                fprintf(stderr, "%s - failed to get byte count on socket.\n", __func__);
                syslog(LOG_ERR, " %s - failed to get byte count on socket.\n", __func__);
                return -1;
        }
        return( (long)nbytes );
}

It is simple and easy to use. It could be placed right after select has returned because data has arrived, perhaps you only want to process packets above a certain byte count.