Set connection timeout for Linux connect

Source: Internet
Author: User

In the past, we basically used the non-blocking method (connect_nonb) in UNIX Network Programming to Implement the connect () Timeout. I saw an article on the Internet today, which is very interesting,ReprintedAs follows:

When I read the Linux kernel source code, I accidentally found that the connect timeout parameter was consistent with the parameter operated with so_sndtimo:

File: net/IPv4/af_inet.c

559 timeo = sock_sndtimeo (SK, flags & o_nonblock );
560
561 if (1 <SK-> sk_state) & (tcpf_syn_sent | tcpf_syn_recv )){
562/* error code is set above */
563 if (! Timeo |! Inet_wait_for_connect (SK, timeo ))
564 goto out;
565
566 err = sock_intr_errno (timeo );
567 if (signal_pending (current ))
568 goto out;
569}

This means that on the Linux platform, you can set so_sndtimo before connect to control connection timeout. Write a test code:


#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>

int main(int argc, char *argv[])
{
        int fd;
        struct sockaddr_in addr;
        struct timeval timeo = {3, 0};
        socklen_t len = sizeof(timeo);

         fd = socket(AF_INET, SOCK_STREAM, 0);
        if (argc == 4)
                 timeo.tv_sec = atoi(argv[3]);
        setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &timeo, len);
         addr.sin_family = AF_INET;
         addr.sin_addr.s_addr = inet_addr(argv[1]);
         addr.sin_port = htons(atoi(argv[2]));
        if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
                if (errno == EINPROGRESS) {
                        fprintf(stderr, "timeout/n");
                        return -1;
                }
                perror("connect");
                return 0;
        }
        printf("connected/n");

        return 0;
}

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.