TCP persistence in C/C ++ Network Programming

Source: Internet
Author: User
Tags keep alive

By default, TCP connections do not have a heartbeat. This means that when a TCP socket, no one from the client and the server sends data, the connection will continue. In this case, if one of the two clients experiences abnormal disconnection, the other end will never know. This will be disastrous for some service-type programs.

Therefore, you must enable the keepalive option for the created socket.

Enable keepalive

For Win32 or Linux platforms, it is easy to set the keepalive of socket. You only need to use setsockopt to set so_keepalive.

The function prototype of setsockopt is as follows in Linux:

[HTML]
View plaincopy

  1. # Include <sys/types. h>
  2. # Include <sys/socket. h>
  3. Int setsockopt (int s, int level, int optname,
  4. Const void * optval,
  5. Socklen_t optlen );

On the Win32 platform

[HTML]
View plaincopy

  1. # Include <winsock2.h>
  2. Int setsockopt (int s, int level, int optname,
  3. Const char * optval,
  4. Int optlen );

Because const void * can accept parameters of the const char * type, you can use the following code to set the keepalive option for cross-platform compilation of the Code.

[HTML]
View plaincopy

  1. Alive = 1;
  2. If (setsockopt
  3. (FD, sol_socket, so_keepalive, (const char *) & alive,
  4. Sizeof alive )! = 0)
  5. {
  6. Log_warn ("set keep alive error: % S. \ n", strerror (errno ));
  7. Return-1;
  8. }

In this way, the default system heartbeat is enabled for TCP connections.

TCP keepalive parameter settings in Linux

Why is it the default value? Because there are several such values, we have not set them manually, It is the default value of the system. That is,

  1. How long does one send a heartbeat packet?
  2. If no response is returned, how long will it take to retry sending?
  3. How many retries are failed?

    For a Linux operating system, the three values are

    [HTML]
    View plaincopy
    1. # Cat/proc/sys/NET/IPv4/tcp_keepalive_time
    2. 7200
    3. # Cat/proc/sys/NET/IPv4/tcp_keepalive_intvl
    4. 75
    5. # Cat/proc/sys/NET/IPv4/tcp_keepalive_probes
    6. 9

In Linux, if the keepalive option is enabled for TCP socket, The keepalive message is initiated after 7200 seconds (that is, two hours) without data. If no response is received, the system will try again in 75 seconds. If all nine retries fail, the connection is deemed invalid. For TCP read operations, 0 is returned.

This is too long for most of our applications.

We can reset the preceding three values to change the behavior of all TCP socket enabled with the keepalive option in the operating system.

We can also reset these three values only for the socket we have created. They correspond to the option values of tcp_keepidle, tcp_keepintl, and tcp_keepcnt respectively. You can also set them using setsockopt.

[HTML]
View plaincopy

  1. # Include <stdlib. h>
  2. # Include <fcntl. h>
  3. # Include <errno. h>
  4. # Include <sys/socket. h>
  5. # Include <netinet/tcp. h>
  6. # Include <netinet/in. h>
  7. # Include <netdb. h>
  8. # Include <ARPA/inet. h>
  9. Int
  10. Socket_set_keepalive (int fd)
  11. {
  12. Int ret, error, flag, alive, idle, CNT, intv;
  13. /* Set: Use keepalive on FD */
  14. Alive = 1;
  15. If (setsockopt
  16. (FD, sol_socket, so_keepalive, & alive,
  17. Sizeof alive )! = 0)
  18. {
  19. Log_warn ("set keepalive error: % S. \ n", strerror (errno ));
  20. Return-1;
  21. }
  22. /* No data in 10 seconds, trigger the retention mechanism, and send the retention package */
  23. Idle = 10;
  24. If (setsockopt (FD, sol_tcp, tcp_keepidle, & idle, sizeof idle )! = 0)
  25. {
  26. Log_warn ("set keepalive idle error: % S. \ n", strerror (errno ));
  27. Return-1;
  28. }
  29. /* If no response is received, resend the live package in 5 seconds */
  30. Intv = 5;
  31. If (setsockopt (FD, sol_tcp, tcp_keepintvl, & intv, sizeof intv )! = 0)
  32. {
  33. Log_warn ("set keepalive intv error: % S. \ n", strerror (errno ));
  34. Return-1;
  35. }
  36. /* If a live packet is not received three times in a row, the connection is considered invalid */
  37. CNT = 3;
  38. If (setsockopt (FD, sol_tcp, tcp_keepcnt, & CNT, sizeof CNT )! = 0)
  39. {
  40. Log_warn ("set keepalive CNT error: % S. \ n", strerror (errno ));
  41. Return-1;
  42. }
  43. Return 0;
  44. }
TCP keepalive parameter settings in Win32 Environment

Parameter settings in the Win32 environment are troublesome. You need to use another function wsaioctl and a structure struct tcp_keepalive.

Their prototypes are:

[HTML]
View plaincopy

  1. # Include <winsock2.h>
  2. # Include <mstcpip. h>
  3. Int wsaioctl (
  4. Socket s,
  5. DWORD dwiocontrolcode,
  6. Lpvoid lpvinbuffer,
  7. DWORD cbinbuffer,
  8. Lpvoid lpvoutbuffer,
  9. DWORD cboutbuffer,
  10. Lpdword maid,
  11. Lpwsaoverlapped lpoverlapped,
  12. Lpwsaoverlapped_completion lpcompletionroutine
  13. );
  14. Struct tcp_keepalive {
  15. U_long Onoff;
  16. U_long KeepAliveTime;
  17. U_long keepaliveinterval;
  18. };

Here, when using wsaioctl, dwiocontrolcode must use sio_keepalive_vals, lpvoutbuffer is not used, and cboutbuffer must be set to 0.

The parameter meaning of the struct tcp_keepalive structure is:

Onoff: whether to enable keepalive; KeepAliveTime; how long does it take to trigger the sending of keepalive packets; keepaliveinterval: How long does it not respond to trigger the next sending.

Note: The two time units here are millisecond rather than second.

[HTML]
View plaincopy

  1. # Include <winsock2.h>
  2. # Include <mstcpip. h>
  3. Int
  4. Socket_set_keepalive (int fd)
  5. {
  6. Struct tcp_keepalive kavars [1] = {
  7. 1,
  8. 10*1000,/* 10 seconds */
  9. 5*1000/* 5 seconds */
  10. };
  11. /* Set: Use keepalive on FD */
  12. Alive = 1;
  13. If (setsockopt
  14. (FD, sol_socket, so_keepalive, (const char *) & alive,
  15. Sizeof alive )! = 0)
  16. {
  17. Log_warn ("set keep alive error: % S. \ n", strerror (errno ));
  18. Return-1;
  19. }
  20. If (wsaioctl
  21. (FD, sio_keepalive_vals, kavars, sizeof kavars, null, sizeof (INT), & ret, null,
  22. Null )! = 0)
  23. {
  24. Log_warn ("set keep alive error: % S. \ n", strerror (wsagetlasterror ()));
  25. Return-1;
  26. }
  27. Return 0;
  28. }

Address: http://blog.csdn.net/weiqubo/article/details/7225338

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.