I inherited some TCP code that called:
bind(tcpSocket, (struct sockaddr*)&server_addr, sizeof(server_addr));
before the call to
setsockopt(tcpSocket, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
Not surprisingly, this lead to the message: "Address already in use". Simply swapping the order of the calls resolved the problem.
This brings up a question: In general, should any calls to setsockopt()
be made before a call to bind()
? Before a call to connect()
?
SO_REUSEADDR
needs to be set before bind()
. However, not all options need to be set before bind()
, or even before connect()
. It really depends on the specific options being set, so you have to deal with them on an option-by-option basis.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With