9

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

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
jski
  • 685
  • 6
  • 14

1 Answers1

9

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.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770