Home > Enterprise >  How does recvfrom know when to stop reading packets?
How does recvfrom know when to stop reading packets?

Time:09-17

in C recvfrom can be used to read UDP messages form a socket as such:

int length = recvfrom(socket, buffer, max_length, 0, NULL, 0);

max_length only tells the maximum number of bytes the buffer can hold, and not the actual length of course.

Assume my message is the following and is sent with sendto:

char *message = "hi";
sendto(sock, message, strlen(message), 0, NULL, 0);

Now recvfrom will immediately stop reading after the i character is received. length will be set to 2. How does it know when to stop?

does sendto append any data to the packet with result of strlen saying what the data length is? or does it look for null terminating char?

CodePudding user response:

Unlike a TCP socket which is stream based, UDP sockets are datagram based.

That means that a single call to sendto will send one UDP datagram and a single call to recvfrom will receive a single UDP datagram. This also means that the buffer supplied to recvfrom should be large enough to hold a single datagram. If it is not large enough, any bytes from that datagram that don't fit in the buffer will be discarded.

  • Related