Whenever my server application receives a packet which is too big for the buffer, it crashes when calling Socket.EndReceiveFrom. This is what my code looks like:
static EndPoint remote = new IPEndPoint(IPAddress.Any, 0);
static Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
static void Main(string[] args)
{
socket.Bind(new IPEndPoint(IPAddress.Any, 1234));
Receive();
Console.WriteLine("Receiving ...");
for (; ; ) ;
}
static void Receive()
{
byte[] buffer = new byte[64];
socket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref remote, ReceiveFromCallback, buffer);
}
static void ReceiveFromCallback(IAsyncResult result)
{
EndPoint theRemote = new IPEndPoint(IPAddress.Any, 0);
byte[] buffer = (byte[])result.AsyncState;
// the following for loop is irrelevant for this question - it simply outputs the received data as hex numbers
for (int x = 0; x < 8; x++)
{
Console.Write(" ");
for (int y = 0; y < 8; y++)
{
string hex = Convert.ToString(buffer[(x * 8) + y], 16);
Console.Write((hex.Length == 1 ? "0" : "") + hex + " ");
}
Console.WriteLine();
}
// the following line of code crashes the application if the received message is larger than 64 bytes
socket.EndReceiveFrom(result, ref theRemote);
}
If the received packets is larger than 64 bytes, my application throws a SocketException saying the following:
A message which was sent over the datagram socket was too large for
the internal data buffer or another network limit, or the buffer used
for receiving the datagram was too small.
Notice that this is not the original message text. Since I’m working with the German version of Visual Studio, I had to translate it back.
ReceiveFromCallback’s “buffer” variable only contains the first 64 bytes of the message if it’s larger than that. So checking whether “buffer” contains more than 64 bytes is not an option.
So my questions are:
Do I need to call EndReceiveFrom(); why should it be called? How can I check whether the received message is too big for the buffer?
From MSDN:
Therefore, you should call EndReceiveFrom in the callback (like you do). Simply catch the exception and your application wont “crash”.