UDP.stop() undocumented

I'm porting a project to the 1.0.1 IDE from 0022 and noticed something with the EthernetUDP library I wanted to verify...

My sketch has a lot of network communication, both with TCP and UDP services and I create sockets dynamically to avoid the 4 limit. However, with the new 1.0.1 UDP library if I create dynamic instances like this:

Udp udp;
udp.begin (port);
udp.beginPacket(serverIP, serverPort);
udp.write ...  

..then I will get a hang eventually which I traced to the UDP begin(). Looking at the Ethernet source I can see it was hitting the 4 socket limitation. So, I was not reaping my UDP instances correctly.

Now I know I can use (up to 4) static instances and it will be fine, but I really wanted to create dynamic instances to keep my memory low so I need to release the UDP instances properly.

The Ethernet library docs do not talk about using stop() for UDP (all the references are only to TCP and 'disconnecting from the server') but I do see a function in the UDP library source called stop() which appears to do the right thing; i.e. it will close the socket and make it available again.

/* Release any resources being used by this EthernetUDP instance */
void EthernetUDP::stop()
  if (_sock == MAX_SOCK_NUM)


  EthernetClass::_server_port[_sock] = 0;
  _sock = MAX_SOCK_NUM;

The last line concerns me; why is it setting _sock to MAX_SOCK_NUM?

So.. is it correct to call UDP.stop() when I'm done sending my datagram and just a doc oversight?
Will calling stop() potentially interfere with a pending datagram from the endPacket()? (I do not like putting arbitrary delays in).


The last line concerns me; why is it setting _sock to MAX_SOCK_NUM?

If MAX_SOCK_NUM is 4, then the valid socket descriptors would be 0, 1, 2, and 3. To make _sock not contain a valid descriptor when the socket it was referring to is no longer being referred to, it needs to contain some non-valid value. That could be -1 or more than the maximum number of sockets.

If _sock is unsigned, that precludes setting it to -1. So, all that is left is setting it to the maximum number of sockets.

Just for others, if you use UDP.stop() it seems to work and I don't seem to need a delay after the endPacket() method before the stop(). Now I can create embryonic UDP instances and close them properly.

I think the UDP documentation and samples should be updated to mention UDP.stop().