Too Long; Don't Read: The difference is whether the source (local) or the destination address/port is being set. In short, bind()
set the source and connect()
set the destination. Regardless of TCP or UDP.
bind()
bind()
set the socket's local (source) address. This is the address where packets are received. Packets sent by the socket carry this as the source address, so the other host will know where to send back its packets.
If receive is not needed the socket source address is useless. Protocols like TCP require receiving enabled in order to send properly, as the destination host send back a confirmation when one or more packets have arrived (i.e. acknowledgement).
connect()
connect()
triggers the TCP code to try to establish a connection to the other side.connect()
only set a default address to where packets are sent when no address is specified. When connect()
is not used, sendto()
or sendmsg()
must be used containing the destination address.When connect()
or a send function is called, and no address is bound, Linux automatically bind the socket to a random port. For technical details, take a look at inet_autobind()
in Linux kernel source code.