How to get past -3005 NSAPI_ERROR_NO_SOCKET returned from socket->connect()

I have firmware that is connected to an app over the internet and I want to be able to lose the connection and restore it. In order to test this I allow the firmware to initialize, including connection to the app. Then, I unplug the ethernet cable. That goes ok, although quite slow. Then I plug the ethernet cable back in. When the firmware tries to connect to the app it fails with an NSAPI_ERROR_NO_SOCKET from socket->connect(). I’ve tried everything I can think of including deleteing the socket and recreating it without success. I even deleted the EthernetInterface and the TCPSocket and started over, but that resulted in a hang that even the watchdog couldn’t pull it out of.
Does anyone know how to get beyond or avoid an NSAPI_ERROR_NO_SOCKET error from socket->connect()when reconnecting?

I have created a sample for using the network event to start/stop a server. It maybe usefull also for a client connection, onEthIfDown() must close and delete the client socket. When the socket is auto created by accept(), it will be automatically deleted on close. I guess the socket is not closed properly and you are running out of free sockets in your case.
The callbacks onEthIfUp/Down are called in the Lwip thread with a small stack, that should be replaced by some other event handling (ran into this problem yesterday).