Search code examples
linuxsocketssocketpair

Why does socketpair() allow SOCK_DGRAM type?


I've been learning about Linux socket programming recently, mostly from this site.

The site says that using the domain/type combination PF_LOCAL/SOCK_DGRAM...

Provides datagram services within the local host. Note that this service is connectionless, but reliable, with the possible exception that packets might be lost if kernel buffers should become exhausted.

My question, then, is why does socketpair(int domain, int type, int protocol, int sv[2]) allow this combination, when according to its man page...

The socketpair() call creates an unnamed pair of connected sockets in the specified domain, of the specified type...

Isn't there a contradiction here?

I thought SOCK_DGRAM in the PF_LOCAL and PF_INET domains implied UDP, which is a connectionless protocol, so I can't reconcile the seeming conflict with socketpair()'s claim to create connected sockets.


Solution

  • Datagram sockets have "pseudo-connections". The protocol doesn't really have connections, but you can still call connect(). This associates a remote address and port with the socket, and then it only receives packets that come from that source, rather than all packets whose destination is the address/port that the socket is bound to, and you can use send() rather than sendto() to send back to this remote address.

    An example where this might be used is the TFTP protocol. The server initially listens for incoming requests on the well-known port. Once a transfer has started, a different port is used, and the sender and receiver can use connect() to associate a socket with that pair of ports. Then they can simply send and receive on that new socket to participate in the transfer.

    Similarly, if you use socketpair() with datagram sockets, it creates a pseudo-connection between the two sockets.