0
votes

Bind function is used to assign a name (a sockaddr struct) to a socket descriptor. Why is it required for TCP server but not TCP client ? And why it is required for bot UDP Client and server?

I have also written correctly working code without using bind() in UDP Client .

I do not understand why bind() is not used universally i.e. in all cases above.

2
AFAIK, connect() implicitly binds unbound sockets (thus assigning source ip:port), as well as listen(), though it is not very useful unless you're using service discovery tool. You may freely bind before connect. - user3125367

2 Answers

5
votes

Binding is only a required, if there is no other way for the computer to know which program to send the packets to. For connection less programs this is only the receiving end.

Please have a look at socket connect() vs bind() this post.

There a much better job of explaining is done than I'm able to do. If you've got any questions after. Feel free to ask:)

2
votes

Client on calling connect implicitly bind to a ephemeral, available port provided by the kernel. It need not specifically bind because it is the initiator of the connection. Server explicitly need to bind because it need to tell external world (the clients) how they can reach the server. Server listens on that port.Client knowing that published port initiates connection to it.

Now servers can send packets to client because on connection establishment the peer details (IP and Port) becomes known and are part of connection identifier.

And the above applied to both TCP and UDP. (UDP will not have connect)