I am using System.Net.Sockets
Socket
class to receive UDP datagrams.
I wanted to know the exact length of the datagram received in order to check the validity of the datagram.
Socket.Receive(Byte())
method documentation says:
If you are using a connectionless Socket, Receive will read the first queued datagram from the destination address you specify in the Connect method. If the datagram you receive is larger than the size of the buffer parameter, buffer gets filled with the first part of the message, the excess data is lost and a SocketException is thrown.
Socket.Available
property gives the total of bytes available to be read, This is sums up the size of all queued datagrams.
Is there a way I can find out the size of the next datagram?
public static void Receive()
{
Byte[] buf, discardbuf;
const int paklen = 32; //correct packet length
int l;
buf = new Byte[paklen];
discardbuf = new Byte[4096];
while (rcv_enable)
{
l = soc.Available;
if (l == 0) continue;
if (l == paklen) soc.Receive(buf); //receive the correct packet
else soc.Receive(discardbuf); //discard otherwise
Thread.Sleep(200);
Console.WriteLine("Received {0}", l);
};
}