Click to See Complete Forum and Search --> : socket data length


mce
June 11th, 2004, 02:50 AM
Hi,

How can i check the available data length in a tcp socket before i go and read it?

I can't use recv(...) with null as the recv buffer to get the available data length... because this function doesn't support that..

UnderDog
June 11th, 2004, 05:30 AM
You cannot get the length from the TCP socket function. In stream oriented protocols the message boundaries have to be application defined. Two methods come to mind

1) Using a flag to indicate the start of the message. The flag may as well be part of the message if it is known that every message starts with a flag. Then to read the message, call recv() with a large buffer, if the message is smaller than buffer u will get the actual number of bytes read. If message is larger than the buffer, then call recv again. You might have to call recev() in a loop.
2) send message length before the message. If length is send as 4 byte integer, then call Recv() first to receive those 4 bytes, that will give you the length, call the second recv() to get those many bytes.

Tron
June 11th, 2004, 01:04 PM
You might want to try

if (ioctlsocket(m_socket, FIONREAD, plBufferSize) == SOCKET_ERROR)
{
// error
}

//returns the amount of data that can be read in a single call
//to the recv function, which may not be the same as the total
//amount of data queued on the socket.

Andreas Masur
June 13th, 2004, 05:25 AM
[Moved thread]

Mathew Joy
June 14th, 2004, 01:14 AM
Originally posted by mce
Hi,

How can i check the available data length in a tcp socket before i go and read it?

I can't use recv(...) with null as the recv buffer to get the available data length... because this function doesn't support that.. The length of the data that has arrived can infact be checked by using the MSG_PEEK flag for recv. But this is bad for many reasons. OTOH, there is no situation that you need to know the length of the data that has arrived before recving. The data that has arrived is for you anyway. Why don't you read it and process it later?

You can find some tips in the following FAQ... (http://www.codeguru.com/forum/showthread.php?s=&threadid=296198) :cool: