Question

This question is related to What does FIONREAD of udp socket return?

I tried to use next code on Mac:

if( ioctl(socketId, FIONREAD, &totalPending) == -1 )
{
    printf("%d", totalPending);
}

numBytesRecv = recvfrom(socketId, buffer, maxLen, 0, socketAddress, &socketAddressLen);

On every call where numBytesRecv != 0, numBytesRecv == totalPending - 16

Can you please explain me why this happens? Is this return value correct? If yes, may I assume numBytesRecv == totalPending - 16 for every value numBytesRecv != 0?

Was it helpful?

Solution

According to the answer to this question, FIONREAD on a Mac returns the size of all available data in the socket's receive buffer, NOT the size of the next pending message. recvfrom() reports the size of just the payload of a received message. So what you are likely seeing is simply FIONREAD reporting additional bytes in the socket's receive buffer that are related to messages after the next pending message. If you need to know the size of the next pending message, use FIONREAD to know when to call recvfrom(), but don't rely on FIONREAD to tell you the actual message size. Instead, call recvfrom() with the MSG_PEEK flag and a large data buffer. The return value will tell you the message size. You can then call recvfrom() again without the MSG_PEEK flag to receive the message and remove it from the receive buffer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top