Network Interface async handling, TCP server restart problem

I’m trying to use the async functions for Ethernet and have created a test program:

The code for the local display can be removed, output is also on stdout.

Working:

  • Bringing the EthIF up or down by plugging / unplugging the network cable
  • Bringing the EthIF up or down by calling connect / disconnect
  • on status change, a TCP socket server is started / stopped
  • connecting with telnet to the socket an receive a hello message

Not Working:

  • after connecting with telnet, a down/up sequence and stop/start server fails with error -3003 (invalid param) on server socket listen().
  • after 120 s, stopping / starting the server works again

The error on listen may happen already on bind(), listen complains at a point where no port is assigned. It looks like the server port is locked for 120 s, this may be by a recommendation that sockets should not be reused for some time?
I guess that it is a Mbed or LwIP bug, what can be the problem?

Output for working case:

EthIF disconnected
sockServer state changed
server stopped
EthIF connecting
EthIF global up
my IP is: 192.168.100.36
server started

non working case:

EthIF disconnected
sockServer state changed
server stopped
EthIF connecting
EthIF global up
my IP is: 192.168.100.36
sockServer listen error: -3003
server started

I cannot answer why you are getting the error. But, do you need to close the TcpSocket when the cable is unplugged? Can’t you just keep it open? It automatically starts working when the connection is reestablished, no?

thanks, I can try that. I thought it is cleaner to shutdown and restart the server, also when a device can be connected to another network.

edit:
yes, your suggestion is working. But I’m still curious why the closed port is locked when I stop the server.

ok, got it.
This is intended behaviour of a listening socket, it is locked for 120 s after closing to avoid problems with delayed incoming tcp packets.
A socket can be immediately reused by setting the reuse option:

    int optval = 1;
    sockServer->setsockopt(NSAPI_SOCKET, NSAPI_REUSEADDR,  &optval, sizeof(optval));