A realization method of the socket connection timeout in Linux

Source: Internet
Author: User
Tags printf set socket socket linux

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; }

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.