How To Use TCP KeepAlive?

This page answers questions like these:

Related Links:
What is TCP KeepAlive?
What Are The Default TCP KeepAlive Parameters?
TCP KeepAlive Parameter Ranges
How Do I Check That TCP KeepAlive Is Working?
Ephemeral Ports



How Do I Use TCP KeepAlive?

The code snippet below can be used in either C++ or C to enable (or disable) KeepAlive for a socket connection in one direction. If running this code on the server side, you should run it on the new socket that comes back from the accept() system call. This is safer than running it on the listening socket and assuming that KeepAlive is inherited across the accept() system call because on some systems it isn’t.

int switch; /* 1=KeepAlive On, 0=KeepAlive Off. */ int idle; /* Number of idle seconds before sending a KA probe. */ int interval; /* How often in seconds to resend an unacked KA probe. */ int count; /* How many times to resend a KA probe if previous probe was unacked. */ /* Switch KeepAlive on or off for this side of the socket. */ if (setsockopt(socket, SOL_SOCKET, SO_KEEPALIVE, &switch, sizeof(switch)) < 0) { /* Error occurred, so output an error message containing: __LINE__, socket, SO_KEEPALIVE, switch, errno, etc. */ } if (switch) { /* Set the number of seconds the connection must be idle before sending a KA probe. */ if (setsockopt(socket, IPPROTO_TCP, TCP_KEEPIDLE, &idle, sizeof(idle)) < 0) { /* Error occurred, so output an error message containing: __LINE__, socket, TCP_KEEPIDLE, idle, errno, etc. */ } /* Set how often in seconds to resend an unacked KA probe. */ if (setsockopt(socket, IPPROTO_TCP, TCP_KEEPINTVL, &interval, sizeof(interval)) < 0) { /* Error occurred, so output an error message containing: __LINE__, socket, TCP_KEEPINTVL, interval, errno, etc. */ } /* Set how many times to resend a KA probe if previous probe was unacked. */ if (setsockopt(socket, IPPROTO_TCP, TCP_KEEPCNT, &count, sizeof(count)) < 0) { /* Error occurred, so output an error message containing: __LINE__, socket, TCP_KEEPCNT, count, errno, etc. */ } }




Related Links:
What is TCP KeepAlive?
What Are The Default TCP KeepAlive Parameters?
TCP KeepAlive Parameter Ranges
How Do I Check That TCP KeepAlive Is Working?
Ephemeral Ports

Home  >  C++ / C  >  How To Use TCP KeepAlive?


Tags: KeepAlive, keep alive, KA, tcp keepalive socket, setsockopt, socket, SOL_SOCKET, SO_KEEPALIVE, IPPROTO_TCP, TCP_KEEPIDLE, TCP_KEEPINTVL, TCP_KEEPCNT, TCP, Transmission Control Protocol, C++, C

Src: tcp-keepalive-how.txt
Dst: C++-C/how-to-use-tcp-keepalive.htm
Ads: 2