Search code examples
csocketstcpudprecvfrom

UDP recvfrom query


int recvfrom(SOCKET            socket, 
             char            * buffer, 
             int               buflen, 
             int               flags, 
             struct sockaddr * from, 
             int             * fromlen);

I know that recvfrom() returns immediately after it reads buflen from socket. My questions here are -

  1. What if i have requested buflen of 2000 and a single packet in the socket queue is of size 2400?

  2. What if i have requested buflen of 2000 and a single packet in the socket queue is of size 1400?

  3. Are the answers for above questions apply same for both TCP and UDP? If not, whats the difference.

Appreciate the reply in advance.


Solution

  • First, recvfrom() only returns immediately if there is already something waiting to be read, or if the socket is in non-blocking mode. Otherwise, it waits for data to arrive.

    Second, UDP is all-or-nothing. Unlike TCP, which operates on streaming data, UDP operates in datagrams instead, and datagrams cannot be read in pieces.

    So, to answer your questions:

    1. 2000 bytes will be copied into your buffer, the remaining 400 bytes are discarded and lost, because your buffer is too small to receive the full datagram. recvfrom() will report an EMSGSIZE error.

    2. your buffer is large enough to receive the full datagram, so 1400 bytes will be copied into your buffer. recvfrom() will report success.

    3. These do not apply the same to TCP. First, you don't typically use recvfrom() with TCP, you use recv() instead. But in either case, in TCP, recv/from() receives whatever bytes are currently available at that moment, blocking if needed, up to the specified number of bytes but may be less. You can keep calling recv/from() to receive the remaining bytes, as TCP is stream-based. Since UDP is message-based, you cannot receive the remaining bytes, they are lost. The next recv/from() will read the next available datagram.