It has been transferred countless times. Continue. Is about TCP Detection

Source: Internet
Author: User
Tags web hosting

At present, I have a case study on the Xinbo function. I have some experiences in using sol_socket and so_keepalive. I 'd like to write it out and share it with you.

There is a detailed description of how to about the sol_socket option so_keepalive. You can see the detailed content on the following webpage.
Http://www.icewalkers.com/Linux/Howto/TCP-Keepalive-HOWTO/index.html

In the UNIX Network Programming 1st volume, it is also described in detail:

So_keepalive keeps the connection to check whether the host of the other party crashes, so as to avoid the (server) from blocking the input of the TCP connection forever. After this option is set, if no data is exchanged in any direction of this interface within two hours, TCP automatically sends a keepalive probe to the other side ). This is a TCP segment that the other party must respond to. It may cause the following three situations: the other party receives everything normally: The expected ack response. 2 hours later, TCP sends out another detection shard. The other party has crashed and restarted: respond with RST. The unhandled error of the Set interface is set to econnreset, And the set interface itself is disabled. The other party has no response: TCP sent from the Berkeley sends an additional eight detection segments, one in 75 seconds, and tries to get a response. 11 minutes after the first probe is sent
If there is no response in 15 seconds, give up. The unhandled error of the Set interface is set to etimeout, And the set interface itself is disabled. For example, if the ICMP error is "Host Unreachable (host inaccessible)", it indicates that the host of the other party has not crashed but is not reachable. In this case, the error to be handled is set to ehostunreach.

On the 158th page of the book, we will provide a more detailed description.

Based on the above introduction, we can know that when the peer is disconnected in an unelegant way, we can set the so_keepalive attribute so that we can find whether the TCP connection of the other party still exists after two hours.

Keepalive = 1;
Setsockopt (listenfd, sol_socket, so_keepalive, (void *) & keepalive, sizeof (keepalive ));

If we cannot accept such a long wait time, we can know from the TCP-keepalive-howto that there are two ways to set, one is to modify the kernel's network configuration parameters, the other options are tcp_keepidle, tcp_keepintvl, and tcp_keepcnt of the sol_tcp field.

The tcp_keepidle parameter specifies the interval of inactivity that causes TCP to generate a keepalive transmission for an application that requests them. tcp_keepidle defaults to 14400 (two hours ).

/* Tcp null close time before the first keepalive test */

 

The tcp_keepintvl parameter specifies the interval between the nine retries that are attempted if a keepalive transmission is not acknowledged. tcp_keepintvl defaults to 150 (75 seconds ).
/* Interval between two keepalive probes */

The tcp_keepcnt option specifies the maximum number of keepalive probes to be sent. The value of tcp_keepcnt is an integer value between 1 and N, where N is the value of the systemwide tcp_keepcnt parameter.

/* Determine the number of keepalive probes before disconnection */

So we can get
Int keepidle = 6;
Int keepinterval = 5;
Int keepcount = 3;

Setsockopt (listenfd, sol_tcp, tcp_keepidle, (void *) & keepidle, sizeof (keepidle ));

Setsockopt (listenfd, sol_tcp, tcp_keepintvl, (void *) & keepinterval, sizeof (keepinterval ));

Setsockopt (listenfd, sol_tcp, tcp_keepcnt, (void *) & keepcount, sizeof (keepcount ));

We need to pay attention to the TCP-keepalive-howto section:

Remember that keepalive is not program −related, but socket −related, so if you have multiple sockets, you can handle keepalive for each of them separately.

These attributes are inherited by sockt, and not all sockets in the Code inherit this attribute, because if you want to apply them to multiple sets of interfaces, you must use setsockopt, respectively, setsockopt is the function of setsockopt.

If the heartbeats function maintains the survival of the client, that is, the server must send a certain amount of data to the client segment at intervals, so_keepalive is insufficient. Because the so_keepalive option indicates "No data is exchanged in any direction of this interface", I don't know how you understand this implementation. In the Linux 2.6 series, the above understanding is that as long as the set of interfaces that enable the so_keepalive option detect data transmission or data acceptance, it is considered as data exchange.

Therefore, in this case, using the so_keepalive option to check whether the other party's abnormal connection is completely ineffective. When packets are sent at intervals, the keep-alive package cannot be sent. The upper-layer program can normally send packets to the buffer zone when an abnormal client is enabled. An exception occurs when the server does not receive a "fin" or "rst" packet.

Of course, this situation is also better to determine whether the other party is alive. The main reason I proposed is to see how everyone understands "there is no data exchange in any direction of this interface.

 

 

 

--------------------------

Windows platforms are also similar:

System-level adjustments can also be made in windows. For Win2k/XP/2003, you can find the parameters that affect all the connections of the entire system from the following registry key:
[HKEY_LOCAL_MACHINE \ SYSTEM \ CurrentControlSet \ Services \ Tcpip \ Parameters]
"KeepAliveTime" = DWORD: 006ddd00
"Keepaliveinterval" = DWORD: 000003e8
"Maxdataretries" = "5 ″
If you set it in the program, first open keep-alive, which is the same as in Linux,
Bool bkeepalive = true;
Int nret =: setsockopt (socket_handle, sol_socket, so_keepalive, (char *) & bkeepalive, sizeof (bkeepalive ));

Then adjust the specific parameters and call wsaioctl.
Tcp_keepalive alive_in = {0 };
Tcp_keepalive alive_out = {0 };
Alive_in.keepalivetime = 5000;
Alive_in.keepaliveinterval = 1000;
Alive_in.onoff = true;
Unsigned long ulbytesreturn = 0;
Nret = wsaioctl (socket_handle, sio_keepalive_vals, & alive_in, sizeof (alive_in), & alive_out, sizeof (alive_out), & ulbytesreturn, null, null );

After the keepalive option is enabled, the getqueuedcompletionstatus function returns false immediately for server programs that use the iocp model once the connection is detected to be disconnected, this allows the server to promptly clear the connection and release resources related to the connection. For the client that uses the select model, when the connection is disconnected, the Select method blocked on the socket for Recv will immediately return socket_error, so that the connection is invalid, the client program will have the opportunity to promptly clear the work, remind the user or reconnect.

 

 

-------------------------------------------------------

Another post is also attached:

As a result, the/etc/hosts quota of the NAS server needs to be frequently used on weekdays to control the NFS access permission for all workstation computers. However, the current requirement is, the host address contained in the hosts must be configured as an instant network traffic control plane. The host traffic control plane must be updated at the same time. this time, Shell and Perl are used to complete all the work.

1) host_list.sh

<Coolcode lang = "ActionScript"> #! /Bin/sh
Path =/bin:/usr/bin
Workdir = "/root/bin"
RHost = "nas.mydomain.com"
Rlname = "myuser"
Tmpdomainfile = "/tmp/hosts. Nas. tmp"

CD $ workdir
# Copy file from remote host
RCP $ rlname @ $ rHost:/etc/hosts $ tmp1_file

# Filter the string we don't need
Linenum = $ (cat-N $ tmp1_file | grep "# for producing" | awk '{print $1 }')
Sed-n "$ linenum, $ P" $ tmp1_file | grep-V "#" </coolcode>

PS. because in the author's environment, the render Control Host is different from the render Control Host. Therefore, the rshell is used to route the local host from the local host nas.mydomain.com hosts/etc/hosts to the local host, and then click it in the left-side navigation pane.
Linenum is developed in concert with the special requirements of our company. This command only allows the list to contain the information we don't need, then the second command is used to parse the line.

2) host_ping.pl

<Coolcode lang = "Perl"> #! /Usr/bin/perl-W

Use Net: Ping;

$ Hostexec = "/root/bin/host_list.sh ";
$ Ping_log = "/LVM/webroot/mon. Server/cgi-bin/ping. log ";

Open (hosts, "$ hostexec |") or die "unable to execute $ hostexec: $! ";
Open (fhd, "> $ ping_log") or die "$! ";
My $ P = net: Ping-> New ('ICMP ');
Print "Please wait 3 minutes... ";
While (($ IP, $ hostname) = Split ('');
My $ result = $ p-> Ping ($ IP, 2 );
My $ now = get_time ();
Print fhd "$ hostname, $ IP, $ result, $ now ";

}
Close (fhd );
Close (hosts );

Sub get_time {
My ($ sec, $ min, $ hour, $ day, $ Mon, $ year) = localtime (time );
$ Mon ++;
If (length ($ Mon) = 1) {$ MON = '0'. $ mon ;}
If (length ($ day) = 1) {$ day = '0'. $ day ;}
If (length ($ hour) = 1) {$ hour = '0'. $ hour ;}
If (length ($ min) = 1) {$ min = '0'. $ min ;}
If (length ($ Sec) = 1) {$ sec = '0'. $ sec ;}
$ Year + = 1900;
My $ alltime = "$ year/$ MON/$ day $ hour: $ min: $ sec ";
}
</Coolcode>

PS. This command will ping all host machine addresses identified by host_list.sh one by one and then ping. log.

3) prodhosts. pl. This is a web hosting. Please put it in a web hosting that supports CGI.

<Coolcode lang = "Perl"> #! /Usr/bin/perl

My $ ping_log = "/LVM/webroot/mon. Server/cgi-bin/ping. log ";

Print "Content-Type: text/html ";
Print <! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en">
<HTML>
<Head>
<Title> tester workstation-network status </title>
<Meta http-equiv = "refresh" content = "300">
<Meta http-equiv = "Pragma" content = "no-Cache">
<Style>
<! -
Tr {background-color: # b5e69d}
. Normal {background-color: # b5e69d}
. Highlight {background-color: # f8ab7c}

//->
</Style>

</Head>

<Body bgproperties = "fixed" background = "/images/bg2.gif">
<P align = "center"> <B style = "color: RGB (51, 51,255);"> tester workstation (UNIX & Linux) -Network Status </B> <br>
</P>
<Center>
<Table Style = "border-collapse: collapse;" border = "1" bordercolor = "#000000" cellpadding = "5" cellspacing = "0" width = "70%">
<Tbody>
<Tr bgcolor = "# d7d1cc">
<TD align = "center" width = "25%"> Host IP </TD>
<TD align = "center" width = "25%"> host name </TD>
<TD align = "center" width = "15%"> host status </TD>
<TD align = "center" width = "35%"> check time </TD>
</Tr>
Html1

Open (fhd, "$ ping_log") or die "$! ";
While (<fhd> ){
Chomp;
My ($ hostname, $ IP, $ stats, $ cktime) = Split (/,/);
Print "<tr onmouseover =" This. classname = 'highlight' "onmouseout =" This. classname = 'normal' "> ";
Print "<TD align =" center "width =" 25% "> $ IP </TD> ";
Print "<TD align =" center "width =" 25% "> $ hostname </TD> ";
Print "<TD align =" center "width =" 15% "> ";
If ($ stats ){
Print " ";
} Else {
Print " ";
}
Print "</TD> ";
Print "<TD align =" center "width =" 35% "> $ cktime </TD> ";
Print "</tr> ";
}
Close (fhd );

Print </Tbody>
</Table>
</Center>
<P align = "center"> <u>
This page designed and maintained by a-Lang of MIS Dept. <br>
</U> </P>
</Body>
</Html>

Html2
</Coolcode>

PS. Modify $ ping_log by yourself.

Results presentation tips:

 

The original article is as follows:

26. Web Programming
This chapter describes the Perl network programming.

26.1 million users remain active
In this case, we want to develop a simple web program to check whether the host you manage is alive.

The program is divided into two parts:

Administrative Program

Refer to the program and present it as a CGI program.

The first is the internal program. This program requires the Net: Ping mode.

First, check whether the system is installed with Ping net? You can use the following methods to check the token:

<Coolcode lang = "Perl"> #! /Usr/bin/perl

Use Net: Ping; </coolcode>

The above is saved as ping. pl, chmod + x ping. pl, and Ping. pl.

If no warning message is displayed, it indicates that the model has been installed. Otherwise, it indicates that there is no security.

If a warning message is reported, you must first ping net: Ping. The security method is as follows:

<Coolcode lang = "ActionScript"> Perl-mcpan-e Shell

CPAN> install net: Ping </coolcode>

Please refer to the security statement in Chapter 1.

26.2 Program
Next, we use net: Ping to compile a simple program, as shown below:

<Coolcode lang = "Perl"> #! /Usr/bin/perl

Use Net: Ping;
Use strict;

# The main website category. Please change it to your current website
My $ prefix = "/home/Apache/htdocs ";

# Log on to Alibaba Cloud
My $ ping_log = "$ prefix/ping. log ";
Open (fhd, "> $ ping_log") | die "$!
";

My $ P = net: Ping-> New ('ICMP ');

# List of IP addresses of the hosts to be renewed. This is just an example. Change it to the IP address of the hosts you manage.
My @ host = QW (
10.1.1.1
10.1.1.2
10.1.1.3
10.1.1.4
10.1.1.222
);

My $ I;
For ($ I = 0; $ I <=$ # host; $ I ++ ){

# Only ping for one second. If the response exceeds one second, there is no response.
# If the value of "allow" $ result is 1, and the value of "allow" $ result is 0
My $ result = $ p-> Ping ($ host [$ I], 1 );

# Obtaining time
My $ now = get_time ();

# Logging in logging into ping. Log
Print fhd "$ host [$ I], $ result, $ now
";
}

Close (fhd );

# Obtain the Time of the sub-Program
Sub get_time {

# Second, minute, hour, day, month, and year
My ($ sec, $ min, $ hour, $ day, $ Mon, $ year) = localtime (time );

# The monthly quota is one less than the actual quota, so 1 is added.
$ Mon ++;

# Determine whether the cursor is a digit. If the cursor is greater than 0
If (length ($ Mon) = 1) {$ MON = '0'. $ mon ;}
If (length ($ day) = 1) {$ day = '0'. $ day ;}
If (length ($ hour) = 1) {$ hour = '0'. $ hour ;}
If (length ($ min) = 1) {$ min = '0'. $ min ;}
If (length ($ Sec) = 1) {$ sec = '0'. $ sec ;}

# The year is 1900 less than the actual Xiyuan, So we add 1900
$ Year + = 1900;

# Complete time for merging
My $ alltime = "$ year/$ MON/$ day $ hour: $ min: $ sec ";

} </Coolcode>

Usage method: (root permission is required to be used)

1. Save the above program as ping. pl and put it in/root.

2. grant permissions to users:

Chmod + x ping. pl

3. Put it in the crontab, and set the row every 5 minutes:

Crontab-u root-e

*/5 */root/ping. pl

26.3 program viewing
Compile a simple CGI program to view the results of the program as follows:

<Coolcode lang = "Perl"> #! /Usr/bin/perl

Print "Content-Type: text/html

";

Print <HTML>
<Head>
<Meta HTTP-EQUIV = "Content-Type" content = "text/html; charset = big5">
<Title> Manage the host survival list </title>
</Head>
<Body bgcolor = "white">
<Table border = 2 align = center>
<Tr> <TD colspan = 3 align = center> <Tr> <TD align = center> host </TD> <TD align = center> Internal Clock </TD> <TD align = center> Clock time </TD> </tr>
Here

# The main website category. Please change it to your current website
My $ prefix = "/home/Apache/htdocs ";

# Log on to Alibaba Cloud
My $ ping_log = "$ prefix/ping. log ";
Open (fhd, "$ ping_log") | die "$!
";

While (<fhd> ){
Chomp;
My ($ host, $ alive_or_not, $ time) = Split (/,/);
My $ status = ($ alive_or_not )? "<Font color = blue> zookeeper </font>": "<font color = Red> zookeeper </font> ";
Print "<tr> <TD> $ host </TD> <TD align = center> $ status </TD> <TD align = center> $ time </TD> </ tr>
";
}

Close (fhd );

Print </Table>
</Body>
</Html>

Here2 </coolcode>

Usage:
1. Save the above program as viewping. cgi and put it in the cgi-bin directory of the web.

2. grant permissions to users:

Chmod + x viewping. cgi

3. Merge rows in the scanner:

Http: // your host/cgi-bin/viewping. cgi

The following are the results of the rows:

Zookeeper

Http://linux.tnc.edu.tw/techdoc/perl_intro/c1225.html

 

 

Although I won't use shell or Perl

However, I think the idea is that Ping can be used for pulling, that is, there are actually many ways, but these layers may be closer to the link layer. First.

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.