Emperon
Emperon

Reputation: 91

Linux: socket and binding issues

Which return value of the function close(socket) on the client side, the server get? Everytime I close the connection from the client side my server closes as well and when I try to reopen it I got : Error in bindind socket: Adddress Alreasy in use.

But I used this function in my server:

n = read(newsockfd, buffer, sizeof(buffer));
if (n < 0) errore("Errore lettura Socket");
if (n == 0) 
                  { 
int true = 1;
setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&true,sizeof(int));
shutdown(sockfd, SHUT_RDWR);
close(sockfd);

}

Upvotes: 0

Views: 430

Answers (1)

Alnitak
Alnitak

Reputation: 339985

To allow rebinding to the same address, the SO_REUSEADDR option must be enabled on the server socket after it has been created, but before the bind() call is made, since it's that call to bind which actually attempts to attach the newly created socket to its intended IP address and port, i.e.

s = socket(...);
result = setsockopt(s, SO_REUSEADDR, ...);
result = bind(s, ...);

Upvotes: 1

Related Questions