While writing a simple UDP server, I had the idea to focus on the differences with a TCP one.
The standard TCP Server flow is the following:
- create TCP socket()
- bind() it to an ip:port address
- listen() for incoming connection
- accept() them
The 1. is done via a socket(.., STREAM, TCP) system call. Replacing STREAM, TCP with DATAGRAM, UDP, and going thru point 2. to 4. we’ll get the following errors:
- listen(): Operation not supported
- accept(): Operation not supported
What happened? Yep, easy: as UDP is a connection-less protocol, we cannot “listen for” or “accept” connection.
While TCP establishes a fixed connection between client and server, an UDP server just gets every single packet which arrives from a client.
You can check this behavior running netcat in udp mode:
#nc -u localhost 12345
This command is successful even if there’s nothing listening on that port: it’s like a cannon ready to fire everything against a castle’s port.
Each time you send something, it fires. And you need to switch it off to “close” it!