Reputation: 1500
I am following a socket programming tutorial and the following code came up
// Forcefully attaching socket to the port 8080
setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT,&opt, sizeof(opt)
From here I see that the third parameter of setsocketopt is an integer which represents option name. After googling about setsockopt I found that almost everywhere only one of SO_REUSEADDR or SO_REUSEPORT is used with setsockopt. In socket.h file value of SO_REUSEPORT is 15 and value of SO_REUSEADDR is 2. My question is what is the purpose of bitwise OR operation in the above code?
Upvotes: 1
Views: 2639
Reputation: 12347
That example is incorrect - or, at least, that construct is non-portable. It appears that BSD-ish Unixes (including MacOS) define those options to be bitmasks, in which case, presumably you can get away with bitwise OR'ing them together. However, setsockopt()
is a Posix-specified function.
See http://pubs.opengroup.org/onlinepubs/9699919799/functions/setsockopt.html, wherein it says:
The option_name argument specifies a single option to set.
You should always call setsockopt()
separately for each option you want to set:
// Forcefully attaching socket to the port 8080
setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
setsockopt(server_fd, SOL_SOCKET, SO_REUSEPORT, &opt, sizeof(opt));
Upvotes: 3