Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should a datagram socket be connected?

Tags:

c

posix

sockets

I am working in C, using the POSIX socket API.

I am not sure when it is appropriate to connect a datagram socket. As I understand it, UDP is connectionless, and SOCK_DGRAM sockets use UDP. So what happens when connect() and accept() are used on datagram sockets?

It seems to me that connecting them and using send()/recv() is easier than not connecting them and using sendto()/recvfrom().

Is there a difference in the functionality of the sockets when connected, or is this just an abstraction?

like image 425
Dakota West Avatar asked Feb 14 '23 13:02

Dakota West


1 Answers

connect() on a datagram socket is appropriate when you want the convenience of a default destination peer for use by send(), rather than explicitly specifying a destination with sendto(). There is no functional difference.

connect()ing to an AF_UNSPEC address will clear the datagram socket's default peer. (This last behavior is widely supported, I think, but only recently formalized.)

connect() on a datagram socket will limits recv()s to data originating from the peer.

accept() on a datagram socket is an error (EOPNOTSUPP), regardless of "connectedness".

like image 144
pilcrow Avatar answered Feb 17 '23 01:02

pilcrow