0

I have a client-server application written in C. A hardcoded port number is used for socket communication between the client and the server. After every run of the application, I have to wait for some time before restarting it again given that the socket enters the TIME_WAIT state after the server exists. If I don't wait, the new run of the server errors out with "Address already in use". My code is based on Beej's Guide to Network Programming. Here is the sequence of calls made on the server side:

sock = socket(...);
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &OK, sizeof(int)); //OK=1
bind(sock, ...);
listen(sock, BACKLOG);
while(someCondition) {
    select(sock+1, &readFDs, NULL, NULL, &timeout);
    newSock = accept(sock, ...);
    recv(newSock,...);
    send(newSock,...); // ACK
    close(newSock);
}
close(sock);
return 0;

On the client side, a connection is established to send a request to the server and then closed as soon as a response is received from the server. The sequence of calls is as follows:

clientSock = socket(...);
connect(clientSock, ...);
send(clientSock, ...);
recv(clientSock, ...);
close(clientSock);

Is there a way to be able to restart the server immediately without having to wait? Can I avoid that the socket created by the server enters the TIME_WAIT state? Is there a way to pick a different port for every run?

Salah
  • 33
  • 5
  • 3
    use SO_REUSEPORT instead - see [How do SO_REUSEADDR and SO_REUSEPORT differ?](https://stackoverflow.com/questions/14388706/how-do-so-reuseaddr-and-so-reuseport-differ). – Steffen Ullrich Nov 04 '20 at 17:45
  • You should make this an answer, @SteffenUllrich ? – tink Nov 04 '20 at 18:26
  • Unfortunately, my Linux version is < 3.9. According to the link you suggested, SO_REUSEPORTis not available. – Salah Nov 05 '20 at 09:27

0 Answers0