0
votes

Let's say I am trying to send data using udp socket. If the data is big then I think the data is going to be divided into several packets and sent to the destination.

At the destination, if there is more than one incoming packets then how to I combined those separated packets into the original packet? Do I need to have a data structure that save all the incoming udp based on the sender ? Thanks in advance..

3

3 Answers

4
votes

If you are simply sending the data in one datagram, using a single send() call, then the fragmentation and reassembly will be done for you, by the transport layer. All you need to do is supply a large enough buffer to recv(), and if all the fragments have arrived, then they will be reassembled and presented to you as a single datagram.

Basically, this is the service that UDP provides you (where a "datagram" is a single block of data sent by a single send() call):

  • The datagram may not arrive at all;
  • The datagram may arrive out-of-order with respect to other datagrams;
  • The datagram may arrive more than once;
  • If the datagram does arrive, it will be complete and correct1.

However, if you are performing the division of the data into several UDP datagrams yourself, at the application layer, then you will of course be responsible for reassembling it too.


1. Correct with the probability implied by the UDP checksum, anyway.

0
votes

You should use TCP for this. TCP is for structured data that needs to arrive in a certain order without being dropped.

On the other hand, UDP is used when the packet becomes irrelevant after ~500 ms. This is used in games, telephony, and so on.

0
votes

If your problem requires UDP, then you need to handle any lost, duplicate, or out-of-order packets yourself, or at least write code that is resilient to that possibility.

http://en.wikipedia.org/wiki/User_Datagram_Protocol

If you can't afford lost packets, then TCP is probably a better option than UDP, since it provides that guarantee out of the box.