UDP sendto/recvfrom


Can I do the following in the Windows C++ programming :

I am sending this from Client side:
      iBytesSent = sendto( socket, BufData,
                  20, 0, (SOCKADDR*) &service,sizeof(service) );

And receiving this at Server end....

      bytesRecv  = recvfrom(socket, RecData, 6,0,
                  (SOCKADDR*) &service, &addrLen);

What I am trying to do here is sent 20 bytes and receive 6 bytes. I am getting -1 error when I do this.

Here is the error detail by WSAGetLastError():

            Message too long.
                      A message sent on a datagram socket was larger than the internal message                               buffer or some   other network limit, or the buffer used to receive a datagram                               was smaller than the datagram itself.

It work in TCP but I need to do it in UDP. Please let me know if this is possible in UDP.

Who is Participating?
You can do it, but you will always get that error telling you that the datagram was too long for the buffer.  The reason it gives you an error is that the unreceived data will be thrown away.  In TCP, data is a stream that you can send and receive in different size chunks.  UDP sends datagrams that are expected to be read in their entirety.  If it's OK for you to lose the rest of the bytes, you can recive only the first 6 and ignore the WSAEMSGZIZE error.
razaAuthor Commented:

Thank you for your responds.

How do I know how many bytes were recevied.
The return value of recvfrom tells you how many bytes you actually read.  If you want to know how long the incoming datagram is, I think you can peek at the input queue using MSG_PEEK in the flags parameter.  This will return to you the length of the incoming data and leave the data in the queue so you can allocate a large enough buffer and then do a normal recvfrom.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.