Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Peeking at a UDP message in c++


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 :)

like image 687
Idov Avatar asked Apr 02 '11 06:04

Idov


2 Answers

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.

like image 94
sarnold Avatar answered Sep 21 '22 07:09

sarnold


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.

like image 40
Ben Voigt Avatar answered Sep 22 '22 07:09

Ben Voigt