简体   繁体   中英

Bind in TCP/UDP Sockets

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 ie in all cases above.

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:)

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 listen s 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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM