How to Use TCP Keep Alive?

This page answers questions like these:

How Do I Use TCP KeepAlive?

Below is a code snippet that you can use in either C++ or C to enable (or disable) KeepAlive for a socket connection. Normally, this would be run on the new socket after calling 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 is and on others 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. */ } }

What Are the Default KeepAlive Parameters?

What Are Minimum and Maximum Values of the KeepAlive Parameters?

How Do I Know If KeepAlive is Working?


Related Links:
What is TCP Keep Alive?
Ephemeral Ports

Home  >  C++ / C  >  How to Use TCP Keep Alive?


Tags: KeepAlive, keep alive, Keep an idle socket connection alive, Detect whether a socket connection is alive, setsockopt, socket, TCP, Transmission Control Protocol, C++, C

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