user15361688
user15361688

Reputation:

Socket UDP handling incoming payloads different sizes

i am struggling with handling paylods with different sizes in my udp socket. My current idea is, find the biggest payload that can be produced, and make a buffer of that size for the socket. This wouldnt be future proof, if i increase my payloads it will fail or be annoying to change everytime. And secondly this would increase all type of calculation time in my server, for example a basic heartbeat packet, which is not that big, but uses 100bytes for it wouldnt be very memory friendly.

Thanks for any suggestions on how to handle this.

Upvotes: 0

Views: 166

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 597961

Just use a max buffer of 65535 bytes, UDP packets can't be larger than that. No need to be tricky using a dynamically sized buffer. recvfrom() will tell you how many bytes it puts in the buffer. And honestly, 64K is small enough to not worry about it wasting memory, unless you are coding for an embedded device.

That being said, if you absolutely want to use a dynamic buffer, then on some platforms, you can use recvfrom() with the MSG_PEEK and MSG_TRUNC flags (Windows does not support MSG_TRUNC on recvfrom() or WSARecvFrom(), only on WSARecvMsg()) to determine the size of the next packet, then size the buffer accordingly, then call recvfrom() again without the flags to read the packet into the buffer.

Upvotes: 2

Related Questions