My task is to implement a two player game played between two computers connected via TCP. One of the requirement is that only the winner is given the choice play again or not. In case the server wins and decides not to play further, the client should restart as a server and accept new connections.
My approach: If game LOST (in client mode), close sockfd and recreate another one. Then use setsockopt to allow rebinding using SO_REUSEADDR, then calling bind.
int yes = 1;
if ( setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1 )
{
perror("setsockopt");
}
if ( bind(sockfd, (struct sockaddr*)&svr, sizeof(svr) ) == -1 )
{
perror("server: bind");
}
But still, I'm getting the same "Address already in use" error. I've tried sleeping for 150 seconds before recreating the socket and this method works.
NOTE: I'm testing this on the same PC. It may work on two linked PCs but its a necessity to make it work on the same PC. Please help.
setsockopt()
) so we can help. – Greg Hewgill