jski
jski

Reputation: 715

When to call setsockopt? Before bind() and connect()?

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()?

Upvotes: 9

Views: 8005

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 598309

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.

Upvotes: 11

Related Questions