At present, the common platform for the set socket (socket) connection Timeout method is:
Creates a socket and sets it to a non-blocking state.
Call connect to the end of the host, if it fails, determine if the errno is einprogress, that is, whether the connection is in progress, if it is, go to step 3, if not, return an error.
Use Select to listen for write-ready events for sockets within a specified timeout, and the connection fails if the select has a listener to prove the connection was successful.
Here is the sample code in the Linux environment:
#include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <errno.h> #include <
time.h> int main (int argc, char *argv[]) {int FD, retval;
struct sockaddr_in addr;
struct Timeval Timeo = {3, 0};
socklen_t len = sizeof (Timeo);
Fd_set set;
FD = socket (af_inet, sock_stream, 0);
if (argc = = 4) timeo.tv_sec = Atoi (argv[3)); Fcntl (FD, F_SETFL, Fcntl (FD, F_GETFL) |
O_nonblock);
addr.sin_family = af_inet;
ADDR.SIN_ADDR.S_ADDR = inet_addr (argv[1]);
Addr.sin_port = htons (atoi (argv[2));
printf ("%d\n", Time (NULL));
if (Connect (fd, (struct sockaddr*) &addr, sizeof (addr)) = = 0) {printf ("connected\n");
return 0; } if (errno!= einprogress) {perror ("connect");
return-1;
} fd_zero (&set);
Fd_set (FD, &set);
retval = Select (FD + 1, NULL, &set, NULL, &timeo);
if (retval = = 1) {perror ("select");
return-1;
else if (retval = 0) {fprintf (stderr, "timeout\n");
printf ("%d\n", Time (NULL));
return 0;
printf ("connected\n");
return 0; }