Connect timeout Control

Source: Internet
Author: User
1. Set the flag bit to non-blocking mode, and call the connect function in non-blocking mode.
2. call connect. Normally, the TCP three-way handshake takes some time, but the non-blocking call will return an error if it cannot be completed immediately. Therefore, einprogress is returned here, indicates that the connection is established but is not completed.
3. fd_set rset and fd_set
Set the current interface bit (using fd_zero (), fd_set () macro), and set the timeout time (struct
Timeval * timeout)
4. Call select (socket, & rset, & Wset, null, timeout)
If the return value is 0, the connection times out.
If you set a timeout value greater than 75 seconds, there is no need to do so, because the connection timeout limit in the kernel is 75 seconds.

I think everyone knows the socket components in network programming. socket is the set interface. In the set interface programming, when we mention the concept of timeout, we can suddenly think of three: sending timeout, receiving
Timeout and select timeout (note:
The select function is not only used to set the interface, but is usually used in programming.) This timeout cannot be set when you connect to the target host. But under normal circumstances
This timeout is long, and connect is a blocking method. A host cannot be connected and can't be tolerated when connect returns. If your program is trying to connect multiple hosts, I'm afraid it will encounter many problems.
When a host cannot be connected, you cannot stand it. If you think you have mastered this method, you don't have to look at it again.
You share. This article is an example of a program in Linux, but the same is true in windows. It is nothing more than changing the name of several functions.
In Linux, there should be two methods to set timeout for connect. One is some parameters of the system. I don't want to talk about this method because I don't know it clearly: P, which is not implemented by programming. Another method is to implement connect timeout in disguise. I want to talk about this method, in principle:
1. Establish socket
2. Set the socket to non-blocking mode.
3. Call connect ()
4. Use select () to check whether the socket descriptor is writable (note that it is writable)
5. Determine the connect () result based on the result returned by select ()
6. Set the socket to the blocking mode (If your program does not need to use the blocking mode, this step is saved, but generally the blocking mode is used, which is easy to manage)
If you are familiar with network programming, you will know how to write your program as soon as I talk about this process. Here is a piece of program I wrote for your reference only.
/******************************
* Time Out For connect ()
* Write by kerl W
******************************/
# Include <sys/socket. h>
# Include <sys/types. h>
# Define time_out_time 20 // connect timeout time 20 seconds
Int main (INT argc, char ** argv)
{
..................
Int sockfd = socket (af_inet, sock_stream, 0 );
If (sockfd <0) Exit (1 );
Struct sockaddr_in serv_addr;
......... // Fill the serv_addr structure with the server address
Int error =-1, Len;
Len = sizeof (INT );
Timeval TM;
Fd_set set;
Unsigned long ul = 1;
IOCTL (sockfd, fionbio, & UL); // sets the non-blocking mode.
Bool ret = false;
If (connect (sockfd, (struct sockaddr *) & serv_addr, sizeof (serv_addr) =
-1)
{
TM. TV _set = time_out_time;
TM. TV _uset = 0;
Fd_zero (& set );
Fd_set (sockfd, & set );
If (select (sockfd + 1, null, & set, null, & TM)> 0)
{
Getsockopt (sockfd, sol_socket, so_error, & error, (socklen_t *) & Len );
If (error = 0) ret = true;
Else ret = false;
} Else ret = false;
}
Else ret = true;
Ul = 0;
IOCTL (sockfd, fionbio, & UL); // set it to blocking mode
If (! RET)
{
Close (sockfd );
Fprintf (stderr, "cannot connect the server! N ");
Return;
}
Fprintf (stderr, "connected! N ");
// The package sending and receiving operations can also be performed below
...............
}

The above code snippet is for reference only and provides some tips for beginners. It mainly uses several functions: Select,
Ioctl,
You can find related information for getsockopt. I will not describe it here. You just need to tap a man in Linux.
<Function Name> you can see its usage.
In addition, I need to note that, although we use IOCTL to set the set interface to non-blocking mode, select itself is blocked, and the blocking time is the time-out from the call of select
The timeval Structure Variable pointed to by the pointer of the last timeval type parameter. The timeval structure is determined by one representing the number of seconds and one representing the number of microseconds.
(Long type). Generally, we can set the number of seconds to 0 (Note: 1 second equals 1 million microseconds ). Another parameter worth mentioning in the select function is the above
The fd_set variable pointer we use. Before the call, this variable contains the delimiters to be checked by the SELECT statement. After the call, the delimiters can be written to the above program.
You can use the macro fd_isset to check whether a descriptor is in it. Because I only have one set of interface descriptors here, I didn't use the fd_isset macro to check
Whether or not sockfd is in set requires this judgment. However, I used getsockopt to check whether the interface is actually connected.
In disguise, we only use select to check whether it is connected. In fact, select checks whether it is writable. For writeable, it indicates writeable when any of the following three conditions is met.
Of:
1) the number of available control bytes in the sending buffer of the Set interface is greater than or equal to the current value at the low tide of the sending buffer of the Set interface, or I) the set interface is connected, or II) connection is not required for the set of interfaces (in UDP Mode)
2) The write half of the connection is closed.
3) There is a set of interface errors to be processed.
In this way, we need to use the getsockopt function to obtain some information about the current interface to determine whether it is actually connected. When there is no connection, what error can be returned, of course, I did not mark so many states in the program, but simply said that they can be connected/not connected.
Next I will talk about the testing results of this program. I tested in three cases:
1. Normal network of the target machine
You can connect to the target host and successfully send and receive packets in blocking mode.
2. Network disconnection of the target machine
After waiting for the set timeout time (20 seconds in the preceding program), it is displayed that the target host cannot be connected.
3. Disconnect the network of the target machine before running the program, and restore the network of the target machine within the timeout period.
Before the network connection of the target host is restored, the program waits for a while. After the target host is restored, the program displays that the target host is successfully connected, and the packet sending and receiving tasks can be completed in blocking mode.
The test results in the above cases show that this method of setting the connect timeout is completely feasible. I encapsulated this timeout-based connect into my own class library and used it in a set of monitoring
In the control system, so far, the operation is still normal. The connection timeout of this programming implementation is a bit better than the method of modifying system parameters because it is only used in your program without affecting the system.

Bytes ---------------------------------------------------------------------------------------------------------------------

In the past, we basically used the non-blocking method (connect_nonb) in UNIX network programming to achieve the connect () Timeout. I saw an article on the internet today and found it interesting. The Reprinted below:

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.