Adit
Adit

Reputation: 31

What exactly is the purpose of setsockopt?

I have built a simple client-server architecture, with a multithreaded echo server handling requests from clients. I have implemented this in C and the server and client fully work as expected. However, I have recently come across the setsockopt system call, and I am not able to understand quite clearly why it is needed. Even after adding it to the server code after socket system call, I did not notice any difference in the program.

if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT,
                                              &opt, sizeof(opt)))

Any pointers on why this is really needed? The man pages and other sites don't seem to answer why it is beneficial clearly.

Upvotes: 2

Views: 5301

Answers (1)

Jeremy Friesner
Jeremy Friesner

Reputation: 73081

setsockopt is short for "set socket option", which pretty well sums up what its purpose is -- as a generic way to set various options for a socket. It's designed to be flexible enough to support both current optional-functionality as well as any additional options that might be added to the network stack in the future, hence the (rather awkward) pass-by-pointer-and-size semantics of the call, which can be used to pass any type or amount of option-configuring data if necessary.

As to the particular options specified (incorrectly, btw) in your code snippet: the SO_REUSEADDR arg tells the OS that calls to bind() this socket are allowed to reuse a local address; this is particularly useful when stopping and then quickly restarting a server, since otherwise the address you want to bind to might still be allocated to the previous server instance, and thus your server won't be able to bind() to it for several minutes.

SO_REUSEPORT tells the OS that you'd like to allow multiple sockets to bind to the same socket address simultaneously; it's useful e.g. when running multiple clients that all want to receive the multicast or broadcast traffic coming in on a given port simultaneously.

For more info about those options, see the socket (7) man page.

Upvotes: 2

Related Questions