Peeking at a UDP message in c++
Asked Answered
A

3

6


I'm trying to receive a UDP message using sockets in c++.
I'm sending the size of the message in the header, so I can know how much memory should I allocate, so I try to peek at the beggining of the message like this:

int bytesRead = recvfrom(m_socketId, (char*)&header, Message::HeaderSize, MSG_PEEK, (struct sockaddr *)&fromAddr, &addrSize);  

but I keep getting system error 10040 :

"A message sent on a datagram socket was larger than the internal message buffer or some other network limit, or the buffer used to receive a datagram into was smaller than the datagram itself."

Is there a way to peek just at the begging of the message?
thanks :)

Alti answered 2/4, 2011 at 6:23 Comment(0)
I
6

Given that the maximum size of a UDP packet is 65507, you could just allocate a single 64k 'bounce buffer' for all your recvfrom() calls -- once you've copied it in, read the size, allocate a new buffer, and make a copy of your packet at exactly the right size.

It is a little wasteful to be copying packet data around so much, but it would let you allocate buffers at the right size.

Or, if you know your peer will never generate packets larger than 8k because of the architecture of your application, you could just allocate 8k buffers and waste the space. Being conscious of memory use is important, but sometimes just burning an extra page leads to simpler code.

Iodize answered 2/4, 2011 at 6:34 Comment(2)
+1 This is the common pattern, I don't know in windows, but in some OS, reading of only part of the message will discard the rest of it, so the common pattern is trying to read the 64k (will return how much the message actually took)Tetrachloride
@David: I would hope that the MSG_PEEK flag prevents anything from being discarded.Sports
S
3

You could try WSARecvMsg(..., MSG_PEEK). You'll get the MSG_TRUNC flag set in the result, but you should also have the header bytes you asked for.

Sports answered 2/4, 2011 at 6:41 Comment(0)
E
1

Your code is actually perfectly fine. You should have read the description of the error code WSAEMSGSIZE (that's your 10040) on the page of recvfrom.

The message was too large to fit into the buffer pointed to by the buf parameter and was truncated.

In your case the error code WSAEMSGSIZE is not really an error, because you are intentionally reading less than the full packet. Just parse your header and then read the full packet without MSG_PEEK to remove the packet from the input queue.

Ehudd answered 17/2, 2015 at 9:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.