Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 407
jski Avatar asked Sep 19 '14 22:09

jski


1 Answers

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.

like image 55
Remy Lebeau Avatar answered Oct 01 '22 22:10

Remy Lebeau