What's the purpose of using sendto()/recvfrom() instead of connect()/send()/recv() with UDP sockets?

jokoon picture jokoon · May 31, 2011 · Viewed 27.2k times · Source

I can grasp the concept of TCP vs UDP, but still I don't know why are there 2 ways of sending UDP packets, and with that I still don't understand if this is absolutely necessary to bind() and accept()...

Answer

Marquis of Lorne picture Marquis of Lorne · Jun 1, 2011
  1. accept() is for TCP. It has nothing to do with UDP.

  2. connect() in UDP doesn't do anything to the other end, it just conditions the local API to know who you are sending to and receiving from.

  3. If you don't already know that, or don't care, or want to send to multiple destinations with the same socket, you don't use connect(), you use sendto() instead. Similarly for receiving.

    Consider a UDP server for example. It would call recvfrom(), so it would get the source address information, process the request, create the response, and send it to that address via sendto(). No connect() involved anywhere, ergo not possible to use either send() or recv().

  4. It is only necessary to bind() a server, because the clients need a fixed port number to send to. A client needn't bind() at all: an automatic bind() will take place on the first send()/sendto()/recv()/recvfrom() using a system-assigned local port number.