How do you go about setting the timeout for the connect( ) function?
How do you go about setting the timeout for the connect( ) function?
Naturally I didn't feel inspired enough to read all the links for you, since I already slaved away for long hours under a blistering sun pressing the search button after typing four whole words! - Quzah
You. Fetch me my copy of the Wall Street Journal. You two, fight to the death - Stewie
Bunch of ways. The easist (IMO) is something like the following
Thats a code segment obviously.Code:FD_ZERO(&set); FD_SET(sock, &set); fcntl(sock, F_SETFL, O_NONBLOCK); if ( (ret = connect (sock, (sockaddr *)&addr, sizeof (sockaddr))) == -1) { if ( errno != EINPROGRESS ) return 0; } ret = select(sock+1, NULL, &set, NULL, &timeout); close(sock);
What you are doing is setting the socket to be non blocking, as such connect will immediatly fail but should errno should be set to EINPROGRESS from there you use select to see if you can write to it. Select is always blocking but has a timeout parameter.
There are also ways using signal() and alarm().
>>from there you use select to see if you can write to it
The socket can be writable if the connect works or if it fails, so you need another level of testing to see if you're actually connected or not.
The following is based on Jon Snader's code from Effective TCP/IP Programming:
You'd call IsSocketConnected() after doing the select().Code:int IsSocketConnected(int fd, fd_set *rd, fd_set *wr) { /* * Code taken from Effective TCP/IP Programming, by Jon Snader, p185 */ int err; size_t len = sizeof(int); errno = 0; if (!FD_ISSET(fd, rd) && !FD_ISSET(fd, wr)) { return(0); } if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &len) < 0) { return(0); } errno = err; return(errno == 0); }
The Windows version looks like so:
Code:int isconnected(SOCKET s, fd_set *rd, fd_set *wr, fd_set *ex) { WSASetLastError(0); if (!FD_ISSET(s, rd) && !FD_ISSET(s, wr)) { return(0); } if (FD_ISSET(s, ex)) { return(0); } return(1); }
When all else fails, read the instructions.
If you're posting code, use code tags: [code] /* insert code here */ [/code]