Setting time out for connect() function tcp socket programming in C breaks recv()
c, tcp
Solution
Setting time out for connect() function tcp socket programming in C is not working
Correction. Setting the connect timeout is working. What 'isn't working' is the subsequent `recvfrom()`, and that's because you left the socket in non-blocking mode and you don't know what to do with the resulting `EAGAIN.` So, either handle that, by using `select()` to tell you when the socket is ready to read, or else put the socket back into blocking mode after finishing the connect.
Problem
In my program If the server is not reachable the connect function take too much time. So i try to give time out to connect using select(). Now the problem is that when i try to receive data from server using recvfrom() i got error "EAGAIN". here is code used to connect and receive data from server. ``` int sock; struct sockaddr_in addr; int connectWithServer { int status; struct timeval timeout; timeout.tv_sec = 10; timeout.tv_usec = 0; addr.sin_port = htons(port); sock = socket (AF_INET,SOCK_STREAM,0); inet_pton(AF_INET,serverIP,&addr.sin_addr); fd_set set; FD_ZERO(&set); FD_SET(sock, &set); fcntl(sock, F_SETFL, O_NONBLOCK); if ( (status = connect(sock, (struct sockaddr*)&addr, sizeof(addr))) == -1) { if ( errno != EINPROGRESS ) return status; } status = select(sock+1, NULL, &set, NULL, &timeout); return status; } long int receiveResponse (void *response , unsigned int length) { socklen_t sockLen = sizeof(struct sockaddr); long int received = recvfrom(sock, response, length, 0,(struct sockaddr *)&addr, &sockLen); printf("Received %ld bytes... err %d\n",received, errno); return received; } ```