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 🙂
Given that the maximum size of a UDP packet is
65507, you could just allocate a single 64k ‘bounce buffer’ for all yourrecvfrom()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.