Getting part of a packet through recvfrom (UDP)

I am trying to get part of a package through recvfrom. It really works as follows:

recvfrom(sockfd, serialised_meta, 12, flags, src_addr, addrlen); recvfrom(sockfd, serialised_buf, BUFLEN, flags, src_addr, addrlen); 

Data is sent as follows:

  bufd->Serialise(serialised_buf, BUFLEN+12); sendto(sockfd, serialised_buf, BUFLEN+12, flags, dest_addr, addrlen); 

So, the idea is to first read some metadata and then decide whether to receive anything else. The problem is that I get 4 '/ 0' bytes at the beginning if the second buffer (serialized_buf). This doesn't seem to be a serialization issue, I used to use serialization, and everything was cool, while I got the whole package (meta and data) at once. Any ideas on how to fix this?

PS. I understand that I can just skip unnecessary bytes) But anyway, why can this happen?

+4
source share
2 answers

UDP is not a "streaming" protocol ... after the initial recvfrom execution, the rest of the packet is discarded. The second recvfrom is waiting for the next package ...

+10
source

UDP works with messages, not streams such as TCP. When using UDP, there is a 1 to 1 relationship between sendto() and recvfrom() . There is no option to get partial data in UDP, this is an all-nothing-type transport. You must recvfrom() whole BUFLEN+12 message at a time, and then decide whether you intend to use it or not. This is how UDP works.

+3
source

Source: https://habr.com/ru/post/1445163/


All Articles