1

What confuses me is that given that sockets are bi-directional, why can't I just open 1 socket with socket() on the client and one on the server and let them communicate over this single socket?

What would be a common use case that I would need a pair of sockets?

Anastasios Andronidis
  • 6,310
  • 4
  • 30
  • 53
  • https://stackoverflow.com/questions/1583005/is-there-any-difference-between-socketpair-and-pair-of-unnamed-pipes/10316382 is a duplicate? – KamilCuk Oct 05 '20 at 18:33
  • Simplicity? With `socketpair` you only need to call a single function. – Some programmer dude Oct 05 '20 at 18:37
  • 1
    `socketpair` is just a fast and convenient way to get an _anonymous_ pair of connected local sockets in your process. It's not strictly necessary, but a lot faster than the equivalent socket/socket/bind/listen/connect steps when those are just overhead for the end goal and would require the kernel to go through a lot of extra steps. – Max Oct 05 '20 at 18:42
  • 1
    The title does not reflect what you actually ask in the question body. In the title you ask about the difference, in the body what socketpair is used for. The answer to the title: socket creates __one__ socket while socketpair creates __two__ sockets which are also __connected__ to each other. – Steffen Ullrich Oct 05 '20 at 18:56
  • Does this answer your question? [Is there any difference between socketpair and pair of unnamed pipes?](https://stackoverflow.com/questions/1583005/is-there-any-difference-between-socketpair-and-pair-of-unnamed-pipes) – рüффп Oct 06 '20 at 08:40
  • Thank you all for your comments, I changed my question. I hope this reflects what I have in mind better. – Anastasios Andronidis Oct 06 '20 at 15:42

2 Answers2

4

So what is the common use case that I would need a pair of sockets?

Typically that you want bidirectional communication between a parent and child process (or sometimes between threads in the same process).

It's like a bidirectional equivalent of pipe, and avoids exposing an AF_UNIX path, or any other publicly-visible address, for something internal to your program.

There's a worked example here.

Useless
  • 64,155
  • 6
  • 88
  • 132
3

socketpair creates two sockets which are already connected to each other. A common use case is the communication between a parent and a child process: the parent creates the socket pair, forks the child and then child and parent can communicate through their end of the socket pair with each other.

Steffen Ullrich
  • 114,247
  • 10
  • 131
  • 172