We all know that a TCP server needs to bind to an interface IP and a local port to listen for incoming TCP connections. On the other hand, a TCP client creates a socket connection by calling connect to the target socket address. The kernel will allocate a port and a local interface for that socket connection. This pair of socket addresses uniquely identifies a TCP socket connection locally. This socket address pair is important because TCP connection is persistent. Without calling connect, a socket connection will not be established, thus we cannot send TCP stream of bytes as a client.

But UDP does not have the same concept of persistent connection as TCP. UDP sends packet but not stream of bytes. You can send packets of bytes perfectly fine without calling connect. This is fine when the socket is bound to a specific interface IP and local port, but it can cause problem for later UDP sockets if no binding operation is explicitly performed, or IDADDR_ANY (0.0.0.0) is used instead of a specific IP.

The problem of not calling connect is that by default it binds to 0.0.0.0, which prevents new socket from binding on any IP address with the same port, including multicast addresses. New socket that tries to bind to any IP addresses with the same port would result in an “address in use” error.

Calling connect before sending data through a UDP socket avoids the “address in use” problem. It is also nice that you don’t need to specify target socket address when you send a packet after connect. Typing one more line of code seems a good trade-off to make, doesn’t it?