How to Set socket connect timeout (Linux)

Source: Internet
Author: User
Tags set socket socket connect
Link: http://gcody.blog.ccidnet.com/blog-htm-do-showone-type-blog-itemid-217292-uid-36931.html

[From] http://dev.cbw.com/c/c/200510195601_4292587.shtml

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. set the current interface bit (using fd_zero (), fd_set () macro) in the read set interface descriptor set (fd_set rset) and write set interface descriptor set (fd_set Wset ), 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.

[From] http://www.ycgczj.com.cn/34733.html
Network
I think everyone knows the socket components in 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 exceeds
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 snippets are for reference only. They also provide some tips for beginners. You can find relevant information for the select, ioctl, and getsockopt functions. I will not repeat the specific usage here, you only need to gently tap a man <Function Name> in Linux to 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.

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.