# Detect TCP client disconnect

**URL:** <https://forums.freertos.org/t/detect-tcp-client-disconnect/7669>\
**Category:** Kernel\
**Created:** [February 12, 2019, 8:16am UTC](https://forums.freertos.org/t/detect-tcp-client-disconnect/7669 "2019-02-12T08:16:29Z")\
**Posts on this page:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![system](https://d2v6vdsk2p900z.cloudfront.net/original/1X/7fc8fdb729c645aab5b20282bbe34e57cb407be6.jpeg) [@system](https://forums.freertos.org/u/system)\
**Post date:** [February 12, 2019, 8:16am UTC](https://forums.freertos.org/t/detect-tcp-client-disconnect/7669/1 "2019-02-12T08:16:29Z")

</div>

**[focusmaarten](https://sourceforge.net/u/focusmaarten/)** wrote on [Tuesday, February 12, 2019](https://sourceforge.net/p/freertos/discussion/382005/thread/4d37f3b08c/#492e):

Hey all,

I’m using FreeRTOS+TCP to start up a small server through which I serve a CLI to a connecting user. I only want a single user connected at a time, so it is important for me to detect a client disconnecting as soon as possible. For now, the only way I’ve found to figure out the client has disconnected, is to try to send or receive something and check the return value from the function.

But, if a client disconnects nicely (i.e. sends a nice TCP FIN message with all the necessary acks going back and forth), the TCP/IP stack knows that the client has disconnected, right? Is there a way I can know right away that the socket has been closed remotely?

---

<div class="post-metadata">

**Author:** ![htibosch](https://d3iykfbgfh8zhg.cloudfront.net/user_avatar/forums.freertos.org/htibosch/32/62_2.png) [@htibosch](https://forums.freertos.org/u/htibosch)\
**Post date:** [February 12, 2019, 10:45am UTC](https://forums.freertos.org/t/detect-tcp-client-disconnect/7669/2 "2019-02-12T10:45:17Z")

</div>

**[heinbali01](https://sourceforge.net/u/heinbali01/)** wrote on [Tuesday, February 12, 2019](https://sourceforge.net/p/freertos/discussion/382005/thread/4d37f3b08c/#09ea):

For your application, `ipconfigTCP_KEEP_ALIVE` will be helpful. It sends mini-packets to the peer, just to test if it is still alive. After 3 times “no answer”, the connection will be broken.

If your TCP server will only have 1 client at the time, consider using `FREERTOS_SO_REUSE_LISTEN_SOCKET`.

Normally, `FreeRTOS_accept()` returns a new socket. The server socket itself will never connect and it will only be used to call accept().  
With the `FREERTOS_SO_REUSE_LISTEN_SOCKET` option, a successful `FreeRTOS_accept()` will return the server socket itself. After the connection has gone, please call `FreeRTOS_closesocket()` for that server socket.  
After that, create a new server socket and call accept() again.

I wrote some code that causes a graceful disconnect [here](https://sourceforge.net/p/freertos/discussion/382005/thread/fe2c5dd342/?limit=250#cfad)

But normally when the peer takes the initialive to disconnect ( like a telnet server ), you can use this type of code:

```auto
    for( ;; )
    {
    BaseType_t xResult;

        xResult = FreeRTOS_recv( xSocket, pcBuffer, sizeof( pcBuffer ), 0 );
        if( ( xResult < 0 ) && ( xResult != -pdFREERTOS_ERRNO_EAGAIN ) )
        {
            break;
        }
		if( xResult > 0 )
		{
			/* Do something with the data received. */
		}
    }

```

Now when the peer sends a shutdown, `FreeRTOS_recv()` will return immediately with `-pdFREERTOS_ERRNO_ENOTCONN` or so.

You can also poll the current status: `FreeRTOS_issocketconnected()`.

Personally I like to use the option `ipconfigSOCKET_HAS_USER_SEMAPHORE`. That allows you to attach semaphore to all sockets. If any socket has an important event ( RX, TX, error, disconnect ), the semaphore will be given to. When using this technique, the sockets are used in a non-blocking way ( e.g. with `FREERTOS_MSG_DONTWAIT` ).  
The main loop will look like this:

```auto
    for( ;; )
    {
		xSemaphoreTake (xMySemaphore, pdMS_TO_TICKS( 10000 ));
		/* Check all sockets in a non-blocking way. */
	}

```

---

<div class="post-metadata">

**Author:** ![system](https://d2v6vdsk2p900z.cloudfront.net/original/1X/7fc8fdb729c645aab5b20282bbe34e57cb407be6.jpeg) [@system](https://forums.freertos.org/u/system)\
**Post date:** [February 12, 2019, 11:09am UTC](https://forums.freertos.org/t/detect-tcp-client-disconnect/7669/3 "2019-02-12T11:09:17Z")

</div>

**[focusmaarten](https://sourceforge.net/u/focusmaarten/)** wrote on [Tuesday, February 12, 2019](https://sourceforge.net/p/freertos/discussion/382005/thread/4d37f3b08c/#7cf8):

Hey Hein, thanks for the very thorough answer 🙂 The semaphore mechanism might be useful, thanks for pointing it out!

---

<div class="post-metadata">

**Author:** ![esr](https://avatars.discourse-cdn.com/v4/letter/e/ba8739/32.png) [@esr](https://forums.freertos.org/u/esr)\
**Post date:** [November 6, 2023, 12:21pm UTC](https://forums.freertos.org/t/detect-tcp-client-disconnect/7669/4 "2023-11-06T12:21:32Z")

</div>

Hi everyone,  
link in Hein reply is not working anymore!

---

<div class="post-metadata">

**Author:** ![aggarg](https://d3iykfbgfh8zhg.cloudfront.net/user_avatar/forums.freertos.org/aggarg/32/4245_2.png) [@aggarg](https://forums.freertos.org/u/aggarg)\
**Post date:** [November 6, 2023, 5:15pm UTC](https://forums.freertos.org/t/detect-tcp-client-disconnect/7669/5 "2023-11-06T17:15:54Z")

</div>

Are you able to use the code snippet he provided?

---

<div class="post-metadata">

**Author:** ![htibosch](https://d3iykfbgfh8zhg.cloudfront.net/user_avatar/forums.freertos.org/htibosch/32/62_2.png) [@htibosch](https://forums.freertos.org/u/htibosch)\
**Post date:** [November 7, 2023, 6:18am UTC](https://forums.freertos.org/t/detect-tcp-client-disconnect/7669/6 "2023-11-07T06:18:16Z")

</div>

Five years ago, I wrote:

> I wrote some code that causes a graceful disconnect [here](https://sourceforge.net).

That post was stored by [sourceforge.net](http://sourceforge.net), today the forum has a different host. All posts have been preserved in the new forum, but the attachments have got lost.

I do not remember what code was in the link, do you? Was it showing code of a Windows TCP client?

Today I made some new code, a simple TCP echo server which shows:

- how a disconnection is detected
- when a graceful shutdown is necessary
- how a graceful shutdown is performed
- how the FIN-flag can be sent along with the last data using the socket option `FREERTOS_SO_CLOSE_AFTER_SEND`

I tested all code in an STM32F4, along with a recent copy of the IP-stack.

[telnet\_session.zip](https://forums.freertos.org/uploads/short-url/A7lbP3WehkOvHQ8EEOmxQMZPhyW.zip) (3.4 KB)

Find a PCAP in the ZIP file, this is the summary:

 ![image](https://d2v6vdsk2p900z.cloudfront.net/original/2X/4/4259b9d7494c5e6030ad735724ba0b9e6d0ca60b.png)

You see that the last steps are combined: sending data along with the FIN flag.

About the attachment telnet\_session.zip:

`telnet_session.pcap `: PCAP of a session between laptop and DUD  
`telnet_main.c `: Create a parent TCP socket and starts a task for every connection  
`telnet_session.c `: Handles a connected child socket

---

<div class="post-metadata">

**Author:** ![esr](https://avatars.discourse-cdn.com/v4/letter/e/ba8739/32.png) [@esr](https://forums.freertos.org/u/esr)\
**Post date:** [November 7, 2023, 2:23pm UTC](https://forums.freertos.org/t/detect-tcp-client-disconnect/7669/7 "2023-11-07T14:23:57Z")

</div>

Hi Hein,  
it is a good example which make clear how handle API return code.  
My problem is however not solved. I opened a [new tread](https://forums.freertos.org/t/tcp-transaction-management-server-send-after-client-shutdown-shut-wr/18465) which has a better title and explanation.
