# FreeRTOS TCP: Forcefully close connected server socket

**URL:** <https://forums.freertos.org/t/freertos-tcp-forcefully-close-connected-server-socket/16378>\
**Category:** Libraries\
**Created:** [December 13, 2022, 10:37am UTC](https://forums.freertos.org/t/freertos-tcp-forcefully-close-connected-server-socket/16378 "2022-12-13T10:37:38Z")\
**Posts on this page:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![daniel-dnil](https://avatars.discourse-cdn.com/v4/letter/d/e495f1/32.png) [@daniel-dnil](https://forums.freertos.org/u/daniel-dnil)\
**Post date:** [December 13, 2022, 10:37am UTC](https://forums.freertos.org/t/freertos-tcp-forcefully-close-connected-server-socket/16378/1 "2022-12-13T10:37:38Z")

</div>

Assuming a device running FreeRTOS TCP which is serving a number of sockets each using the FREERTOS\_SO\_REUSE\_LISTEN\_SOCKET option. A client has connected and the device has “accepted()” that connection. If the device now would like to “kick out the user” which is connected to this socket, which API calls should the application perform? I’ve attempted to simply call FreeRTOS\_shutdown() on the socket from the application side which works, but it takes around 38 seconds before a new client can connect (assuming this is related to hang and/or keep alive since both options are enabled). Is there a faster way to achieve this on the device side?

---

<div class="post-metadata">

**Author:** ![hs2](https://avatars.discourse-cdn.com/v4/letter/h/a4c791/32.png) [@hs2](https://forums.freertos.org/u/hs2)\
**Post date:** [December 13, 2022, 10:38pm UTC](https://forums.freertos.org/t/freertos-tcp-forcefully-close-connected-server-socket/16378/2 "2022-12-13T22:38:28Z")

</div>

Do you also finally `FreeRTOS_closesocket` ?  
Have a look here for an example howto gracefully close a connection:

> **[TCP Networking Tutorial - Shutting down and closing a TCP socket](https://www.freertos.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/TCP_Networking_Tutorial_Closing_A_TCP_Socket.html)**
>
> Shuting down and closing a TCP socket

BTW FREERTOS\_SO\_REUSE\_LISTEN\_SOCKET allows only 1 socket connection as documented here [FreeRTOS\_listen API reference](https://www.freertos.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/API/listen.html)

---

<div class="post-metadata">

**Author:** ![daniel-dnil](https://avatars.discourse-cdn.com/v4/letter/d/e495f1/32.png) [@daniel-dnil](https://forums.freertos.org/u/daniel-dnil)\
**Post date:** [December 14, 2022, 5:29pm UTC](https://forums.freertos.org/t/freertos-tcp-forcefully-close-connected-server-socket/16378/3 "2022-12-14T17:29:26Z")

</div>

> [@hs2](#):
>
> Do you also finally `FreeRTOS_closesocket` ?

Yes, I call FreeRTOS\_closesocket() and follow the recommended graceful shutdown. So the solution all “works”, but it takes a lot longer than anticipated. So my question is if the time between I call FreeRTOS\_shutdown() and until read returns error can be shortened or if there is a faster non-graceful way of doing this.

FREERTOS\_SO\_REUSE\_LISTEN\_SOCKET is used to intentionally only allow 1 connection at a time. The device is a 5 port TCP socket to UART serial port terminal server so I’m only interested in having 1 client connected at a time since the TCP socket has a 1:1 mapping to the physical UART ports. The issue is in rare cases where the host connecting the terminal server crashes and the host doesn’t properly disconnect, I’d like to via a REST API on another port be able to “kick out” lingering and bad host connections quickly. Device is typically installed in continuous integration automation so there is little user intervention possible.

---

<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:** [December 17, 2022, 7:30am UTC](https://forums.freertos.org/t/freertos-tcp-forcefully-close-connected-server-socket/16378/4 "2022-12-17T07:30:23Z")

</div>

Here is an example of a typical shutdown sequence:

```c
    /* Finished using the connected socket, initiate a graceful close:
    FIN, FIN+ACK, ACK. */
    FreeRTOS_shutdown( xSocket, FREERTOS_SHUT_RDWR );
    
    /* Expect FreeRTOS_recv() to return an error once the shutdown is
    complete. */
	/* Let it last at most 4 seconds. */
	static const TickType_t xReceiveTimeOut = pdMS_TO_TICKS( 4000 );
    TickType_t xTimeOnEntering = xTaskGetTickCount();
    do
    {
        xReturned = FreeRTOS_recv( xSocket, &( pcBuffer[0] ), sizeof( pcBuffer ), 0 );
    
        if( xReturned < 0 )
        {
            break;
        }
    
    } while( ( xTaskGetTickCount() - xTimeOnEntering ) < xReceiveTimeOut );

```

It should last less than 100 ms.

I would be curious to see a PCAP made on the PC that connects to the TCP device. Somewhere a device seems to be waiting for a time-out.

Also if you like, send some of the TCP handling code.

[Hartmut](https://forums.freertos.org/u/hs2) wrote:

> BTW FREERTOS\_SO\_REUSE\_LISTEN\_SOCKET allows only 1 socket connection as documented here FreeRTOS\_listen API reference

Normally a server socket can be used for ever, but when it is a “REUSE” socket, the server socket must be created again.  
You can create a new server socket before the earlier socket is closed.

Another method would be the folllowing: do not use `FREERTOS_SO_REUSE_LISTEN_SOCKET` and call listen() with `xBacklog` = 2.

1. A TCP connected is established and everything works fine.
2. A new TCP connection comes in, and it will take over.
3. The connection 1 is now put aside and it will follow the above shutdown sequence.
4. In a meanwhile the new connection will do the job.

There will be no need to close and re-create the TCP server socket.

---

<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:** [December 17, 2022, 8:15am UTC](https://forums.freertos.org/t/freertos-tcp-forcefully-close-connected-server-socket/16378/5 "2022-12-17T08:15:30Z")

</div>

I just looked at how a TCP connection is shut down normally, see attachment : [shutdown\_session.zip](https://forums.freertos.org/uploads/short-url/tdyTrYOJVjUpmdFfnDsC2IbSlnw.zip) (620 Bytes)

Or visualised here:

 ![image](https://d2v6vdsk2p900z.cloudfront.net/original/2X/7/727bf2175efcf444531be64f72caec87c8de7ac3.png)

It takes less than a ms before the connection is actually closed.

You could also just close the socket, hoping that the remote end sends another TCP packet. When that happens, the FreeRTOS device will reply with a RST.

Would it be possible for you to attach a PCAP recording?

---

<div class="post-metadata">

**Author:** ![RAc](https://d3iykfbgfh8zhg.cloudfront.net/user_avatar/forums.freertos.org/rac/32/1389_2.png) [@RAc](https://forums.freertos.org/u/RAc)\
**Post date:** [December 17, 2022, 8:51pm UTC](https://forums.freertos.org/t/freertos-tcp-forcefully-close-connected-server-socket/16378/6 "2022-12-17T20:51:52Z")

</div>

If I read Daniel’s description correctly, then his problem occurrs when the peer crashes and therefore can not handle a graceful shutdown.

If I remember my RFC 793 correctly, this scenario means that the device will leave its TCP connection in the TIME\_WAIT timeout state. @htibosch : What is the FreeRTOS+TCP setsocketopt to set the time-wait timeout?

---

<div class="post-metadata">

**Author:** ![daniel-dnil](https://avatars.discourse-cdn.com/v4/letter/d/e495f1/32.png) [@daniel-dnil](https://forums.freertos.org/u/daniel-dnil)\
**Post date:** [December 19, 2022, 7:58pm UTC](https://forums.freertos.org/t/freertos-tcp-forcefully-close-connected-server-socket/16378/7 "2022-12-19T19:58:50Z")

</div>

Hi,

Many thanks for valuable feedback! I’ve performed some captures using wireshark, here’s a link to the results (not allowed to post attachments or links…):

`https://drive.google.com/file/d/1a1qKAWb7LYqa5txqtpqlqwle5eXwZdRV/view?usp=share_link`

In ts500\_shutdown\_no\_traffic.pcapng I open a connection from host (192.168.2.50) to the device (192.168.2.50 port 3301). Then I issue a HTTP request to port 80 which executes a portrelease action on the device which in turn performs a FreeRTOS\_shutdown() on the socket from the device side. Device sends FIN, ACK and the host responds with ACK and then nothing more happens. Socket is in CLOSE\_WAIT on the host side until I send some data on it around 642 secs into the trace which is the PSH, ACK → RST, ACK sequence.

In ts500\_shutdown\_try\_open.pcapng I have basically the same scenario but after FreeRTOS\_shutdown() I attempt to issue a new connection to device port 3301 from the host, this doesn’t work since the port is “busy” on the device side. Port is closed and ready for new connection first when the host sends data on the first port opened.

@RAc : Yes, you understood the requirement correctly. In a real scenario the host TCP/IP stack basically goes away, that stack is running inside some virtual machine which may crash and disappear (out of memory kill etc). This scenario is hard to reproduce, so in my test here I run against my desktop Linux host.

I wonder though after studying this in more detail if I have a problem on the application side on the device. The sockets maintained by the device are all members of a socket set using FreeRTOS\_FD\_SET() call, after device application calls FreeRTOS\_shutdown() it expects a negative return value from FreeRTOS\_recv() before calling FreeRTOS\_closesocket(). But actually performing the FreeRTOS\_recv() call on this socket is not done until FreeRTOS\_select() actually indicates that something happened on this socket. Maybe this is what is missing? FreeRTOS\_select() is not returning that the socket which the application has tried to close is readable after FreeRTOS\_shutdown() was called on it? Mask set on FreeRTOS\_FD\_SET() is eSELECT\_READ | eSELECT\_EXCEPT, is this not enough?
