Connect timeout for C socket Programming (RPM)

Source: Internet
Author: User

The component of socket in network programming I think we all know, socket is a socket, in the socket programming, mention the concept of timeouts, we can think of 3: Send timeout, receive timeout, and select timeout (note: The Select function is not used only for the socket interface, However, in the case of socket programming, this timeout is not set by us when connect to the target host. However, under normal circumstances this timeout is very long, and connect is a blocking method, a host can not connect, waiting for connect to return can endure, your program if you want to try to connect multiple hosts, I am afraid to encounter multiple hosts can not be connected to the time, will be stuffed you can not stand. I also talk less, first talk about my method, if you think you have mastered this method, you will not have to watch, if you do not understand, I would like to share with you. This article is already under the Linux program as an example, but to get windows in the same way, nothing but a few function names.

There are two ways to set the time-out for connect in Linux. One is some of the system parameters, this method I do not speak, because I do not know: P, it is not programmed to achieve. Another way is to realize the timeout of connect in disguise, I want to talk about this method, the principle is this:

1. Creating sockets

2. Set the socket to non-blocking mode

3. Call Connect ()

4. Use Select () to check if the socket descriptor is writable (note that it is writable)

5. Determine the Connect () result based on the results returned by select ()

6. Set the socket to block mode (if your program does not need blocking mode, this step is saved, but generally it is in blocking mode, which is also easy to manage)

If you are familiar with network programming, in fact, I say this process you know how to write your program, the following gives me to write a program, for reference only.

/******************************

* Time out for connect ()

* Write by Kerl W

******************************/

#include <sys/socket.h>

#include <sys/types.h>

#define TIME_OUT_TIME//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;

....//populate the structure with the server address serv_addr

int Error=-1, Len;

len = sizeof (int);

Timeval TM;

Fd_set set;

unsigned long ul = 1;

IOCTL (SOCKFD, Fionbio, &ul); Set to 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 to blocking mode

if (!ret)

{

Close (SOCKFD);

fprintf (stderr, "Cannot Connect the server!/n");

Return

}

fprintf (stderr, "connected!/n");

The following can also be done by the package delivery operation

...............

}

The above code snippets, for reference only, but also for beginners to provide some hints, the main use of several functions, select, IOCTL, getsockopt can find relevant information, specific usage I do not repeat here, you just need to tap a man in Linux a < function name > will be able to see its usage.

In addition, I need to explain that although we use the IOCTL to set the socket interface to non-blocking mode, but the select itself is blocked, The time it is blocked is determined by the TIMEVAL structure variable to which the last parameter of the Timeval type is invoked when the select is called, and the Timeval structure consists of a member representing the number of seconds and one that represents the number of microseconds (long). In general we set the number of seconds on the line, set the subtle number to 0 (note: 1 seconds equals 1 million microseconds). Another parameter worth mentioning in the Select function is the variable pointer of the Fd_set type we used above. Before the call, this variable contains a descriptor to be checked with a SELECT, after the call, for the above program is a writable descriptor, we can use the macro fd_isset to check whether a descriptor is in it. Since I have only one set of interface descriptors here, I have not used the Fd_isset macro to check whether the SOCKFD is in set after the call to select, in fact it is necessary to add this judgment. But I used the getsockopt to check, so that we can determine whether the interface is really connected, because we just disguised in a select to check whether it is connected, in fact, select Check is whether it can be written, and for the writable, is writable when either of the following three conditions is satisfied:

1) The number of available controls in the set interface send buffer is greater than the current value of the set interface send buffer low tide limit, and either I) the socket interface is connected, or II) the socket does not require a connection (UDP mode)

2) The connection writes this half off.

3) There is a set of interface errors pending processing.

In this way, we need to use the GETSOCKOPT function to obtain some current information on the socket interface to determine whether it is really connected, when there is no connection on the time can also give the error occurred, of course, I do not mark the program so many states, just simple means can be connected/not connected.

Let me turn to the results of this program test. I tested 3 scenarios:

1. Target Machine Network normal condition

You can connect to the target host and successfully block the packet delivery job.

2. The condition of the target machine network disconnection

After waiting for the set timeout (20 seconds in the program above), the display destination host cannot connect.

3. Disconnect the target machine network before the program runs, and restore the target machine's network within the timeout period

Before recovering the target host network connection, the program waits until the target host is restored, the program shows that the connection target host is successful, and can successfully block the package delivery job.

The test results of each of these conditions indicate that the method of setting up connect timeout is completely feasible. I myself have this set up the timeout of connect to their own class library, used in a set of monitoring system, so far, the operation is normal. This programming implementation of the Connect timeout is a bit more than the method of modifying the system parameters, which is only used in your program without affecting the system.

Connect timeout for C socket Programming (RPM)

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.