How to implement the Connect function with timeout function
Principle:
Looking at man connect today, I understand the cause of the mistake:
Einprogress
The socket is non-blocking and the connection
cannot be completed immediately. It is possible
To select (2) or poll (2) for completion by
Selecting the socket for writing. After
Select (2) indicates writability, use getsock-
Opt (2) to read the So_error option at level
Sol_socket to determine whether connect () com-
Pleted successfully (So_error is zero) or unsuc-
Cessfully (So_error is one of the usual ERROR
Codes listed here and explaining the reason for the
Failure).
Realize:
#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>
#include <arpa/inet.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));
int SAVEFL = FCNTL (FD,F_GETFL);
Fcntl (FD, F_SETFL, SAVEFL | 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)
{
Close (FD);
printf ("Connected ...") 1/n ");
return 0;
}
if (errno!= einprogress)
{
Close (FD);
Perror ("Connect ...") 2 ");
return-1;
}
Fd_zero (&set);
Fd_set (FD, &set);
retval = Select (FD + 1, NULL, &set, NULL, &timeo);
if (retval = = 1)
{
Close (FD);
Perror ("select");
return-1;
}
else if (retval = 0)
{
Close (FD);
fprintf (stderr, "timeout/n");
printf ("%d/n", Time (NULL));
return 0;
}
if (Fd_isset (fd,&set))//| | Fd_isset (Sockfd,&wset))
{
int error = 0;
socklen_t len = sizeof (error);
if (getsockopt (FD, Sol_socket, So_error, &error, &len) < 0)
{
Close (FD);
printf ("getsockopt fail,connected fail/n");
return-1;
}
if (Error = = etimedout)
{
printf ("Connected timeout/n");
}
if (Error = = econnrefused)
{
Close (FD);
printf ("No One listening on the remote address./n");
return-1;
}
}
printf ("Connected ...") 3/n ");
Fcntl (FD, F_SETFL, SAVEFL);
Close (FD);
return 0;
}