I'm trying to set socket options for a client socket returned from the accept() function. But they are not getting set correctly.
My aim is to time out the client after a particular time of inactivity. But the server should still be able to accept other client connections.
Below is my code where I set the socket option. Can you please suggest what is wrong?
while ((new_sock_fd = accept(socket_fd, (struct sockaddr *) &cli_addr, &clilen)) > 0)
{
if (new_sock_fd < 0)
printf("Accept Error");
else
{
struct timeval timeout;
timeout.tv_sec = 10;
timeout.tv_usec = 0;
if (setsockopt(new_sock_fd, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout)) < 0)
error("setsockopt failed\n");
if (setsockopt(new_sock_fd, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout, sizeof(timeout)) < 0)
error("setsockopt failed\n");
pthread_create(&thread, NULL, client_handler, (void *) (intptr_t)new_sock_fd); //intptr_t is big enough to hold the integer prt
}
}
setsockopt()failing with an error? Doesgetsocktop()return values you are not expecting? Does the socket simply behave differently than expected? If so, how? What platform is this code running on? On most platformsSO_RCVTIMEOandSO_SENDTIMEOdo indeed take atimevalstruct as input. But on Windows, they take aDWORDinstead. - Remy LebeauAccept Errormessage will never be reported, since your loop only enters the loop body whennew_socket_fd > 0. If you want to do error handling onaccept(), you should move it inside the loop instead. - Remy Lebeau