Search code examples
udpsendtorecvfrom

UDP message size difference


Say that A sends B a UDP message of size N like

sockaddr_in to;
to.sin_family=AF_INET;
to.sin_port=htons(port);
to.sin_addr.s_addr=inet_addr(address);
sendto(sock,(const char*)buffer,N,0,(sockaddr*)&to,sizeof(to));

Now B receives this message expecting it to be of size N_1

sockaddr from;
socklen_t length_from=sizeof(from);
recvfrom(sock,(char*)buffer,N_1,0,&from,&length_from);

What happens when N_1!=N ?


Solution

  • What happens when N_1!=N ?

    If the receive buffer is larger than the incoming datagram, the entire datagram is transferred into the buffer and the actual length is returned as the return value of recfvrom(). You're presently ignoring it. Don't do that.

    If the receive buffer is smaller than the incoming datagram, it is truncated to fit into the receive buffer and he excess beyond that is discarded. The actual length of data transferred into the buffer is returned.