Peeping a UDP message in C ++


I am trying to get a UDP message using sockets in C ++.
I am sending the message size in the header, so I can know how much memory I should allocate, so I try to look at the top of the message as follows:

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

but I get system error 10040 all the time:

"The message sent to the datagram socket was larger than the internal message buffer or some other network limit, or the buffer used to receive the datagram in was smaller than the datagram itself."

Is there a way to spy on begging messages?
thanks:)

+6
c ++ windows udp peek
source share
3 answers

Given that the maximum size of a UDP packet is 65507 , you can simply allocate one 64k buffer for all your recvfrom() - after you copy it, read the size, select a new buffer and make a copy of your packet exactly in the right size.

It is a little wasteful to copy batch data so much, but it will allow you to allocate buffers with the right size.

Or, if you know that your peer will never generate packets larger than 8 thousand in size due to the architecture of your application, you can simply allocate 8 thousand buffers and lose space. Awareness of memory usage is important, but sometimes just burning an extra page simplifies the code.

+6
source share

You can try WSARecvMsg(..., MSG_PEEK) . You will receive the MSG_TRUNC flag specified as a result, but header bytes must also be requested.

+3
source share

Your code is really great. You should have read the description of the WSAEMSGSIZE error WSAEMSGSIZE (that is your 10040 ) on the recvfrom page.

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

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

0
source share

All Articles