Linux - ioctl with FIONREAD always 0

Toby picture Toby · Aug 8, 2011 · Viewed 53.8k times · Source

I'm trying to get to know how many bytes there are readable at my TCP socket. I am calling ioctl with the Flag "FIONREAD" which should actually give me this value. When I call the function I get as return val 0 ( so no Error ) but also my integer argument gets the value 0. That would be no problem but when I call the recv() method I actually read some Bytes out of the socket. What am I doing wrong?

// here some Code:

char recBuffer[BUFFERLENGTH] = {0};
int bytesAv = 0;
int bytesRead = 0;
int flags = 0;
if ( ioctl (m_Socket,FIONREAD,&bytesAv) < 0 )
{
    // Error
}
if ( bytesAv < 1 )
{
    // No Data Available
}
bytesRead = recv(m_Socket,recBuffer,BUFFERLENGTH,flags);

When I call the recv function i acutally read some valid Data ( which I expected )

Answer

cnicutar picture cnicutar · Aug 8, 2011

It's happening very quickly, that's why you don't see anything. What you're doing:

  • ioctl: Is there data for me ? No, nothing yet
  • recv: Block until there is data for me. Some (short) time later: Here is your data

So if you really want to see FIONREAD, just wait for it.

/* Try FIONREAD until we get *something* or ioctl fails. */
while (!bytesAv && ioctl (m_Socket,FIONREAD,&bytesAv) >= 0)
    sleep(1);