Home > front end >  Purported UDP "connection"
Purported UDP "connection"

Time:02-03

My understanding was that UDP doesn't form connections; it just blindly sends packets. However, when I run

nc -u -l 10002

and

nc -u 127.0.0.1 10002

simultaneously (and so can send messages back and forth between terminals), lsof reports two open UDP connections:

nc ... UDP localhost:10002->localhost:35311 
nc ... UDP localhost:35311->localhost:10002 

If I open a third terminal and do nc -u 127.0.0.1 10002 again, to send another message to the original listener, the listener does not receive (or acknowledge, at least) the message, suggesting it is indeed tied to a specific connection.
If I implement a UDP echo server in Java like this and do sorta the same thing (on 10001), I get

java ... UDP *:10001
nc ... UDP localhost:52295->localhost:10001

aka, Java is just listening on 10001, but nc has formed a connection.

Based on my understanding of UDP, I'd expect both sides to behave like the Java version. What's going on? Can I make the Java version do whatever nc is doing? Is there a benefit to doing so?

I'm on Ubuntu 20.04.3 LTS.

CodePudding user response:

UDP sockets can be connected (after a call to connect) or they can be unconnected. In the first case the socket can only exchange data with the connected peer, while in the second case it can exchange data with arbitrary peers. What you see in lsof is if the socket is connected or not.

My understanding was that UDP doesn't form connections; it just blindly sends packets.

That's a different meaning of the term connection here. TCP has always "real" connections, i.e. an association between two endpoints which has a clear start (SYN based handshake) and end (FIN based teardown). TCP sockets used for data exchange are therefor always connected.

UDP can have associations between two endpoints too, i.e. it can have connected sockets. There is no explicit setup and teardown of such a connection though. And UDP sockets don't need to be connected. From looking at the traffic it can therefore not be determined if connected UDP sockets are in use or unconnected.

Can I make the Java version do whatever nc is doing?

Yes, see What does Java's UDP DatagramSocket.connect() do? .

Is there a benefit to doing so?

An unconnected UDP socket will receive data from any peer and the application has to check for each received datagram where they came from and if they should be accepted. A connected UDP socket will only receive data from the connected peer, i.e. no checks in the application are needed to check this.

Apart from that it might scale better if different sockets are used for communication with different peers. But if only few packets are exchanged with each peer and/or if one need to communicate with lots of peers at the same time, then using multiple connected sockets instead of a single unconnected one might mean too much overhead.

  •  Tags:  
  • Related