3
votes

I have a question about socket programming. When I use socket to send the data, we can use the API such as sendto() to send using TCP or UDP. For sendto(), we give a array pointer and the byte number we want to send.

In this case, if I gave a large byte number (e.g.: 20000 bytes), based on my understanding, MTU of the network will not be that big so socket actually send mutiple packets instead of one big packet. Since these 20000 bytes are split into several UDP/TCP packets, but will these 20000 bytes be seen as one packet at beginning? Is this process UDP/TCP fragmentation ?

My another question is if I put the data size smaller than MTU into sendto(), then I can gurantee call sendto() once, socket only sends one TCP/UDP packet?

Thanks in advance.

1
UDP will not fragment data the way you describe. UDP is a message-oriented transport. What you send on a UDP socket will always be sent as a single packet, or no packet at all. TCP, on the other hand, is a stream-oriented transport and will happily break up data as needed to fit network buffers. The return value of send()/sendto() will tell you exactly how many bytes were actually accepted for transmission, you have to pay attention to it.Remy Lebeau

1 Answers

3
votes

will these 20000 bytes be seen as one packet at beginning? Is this process UDP/TCP fragmentation?

  1. UDP will send it as one datagram if your socket send buffer is large enough to hold it. Otherwise you will get EMSGSIZE. It may subsequently get fragmented at the IP layer, and if a fragment gets lost so does the whole datagram, but if all the fragments arrive the entire datagram will be received intact.

  2. TCP wil send it all, segmenting and fragmenting it however it sees fit. It will all arrive, intact and in order, unless there is a long enough network outage.

My another question is if I put the data size smaller than MTU into sendto(), then I can guarantee call sendto() once, socket only sends one TCP/UDP packet?

  1. UDP: yes.
  2. TCP: no.