connecting a socket
If a server is the shop waiting by its phone, connecting is the customer dialing the shop's number. connect is the client-side call that reaches out to a specific server address and port and, for TCP, sets up the conversation. It is the active opener — the side that initiates — to the server's passive listen-and-accept.
In code, after creating a socket you call connect(fd, server_address), giving the destination IP and port. For a TCP socket this triggers the three-way handshake: your machine sends a SYN, the server replies SYN-ACK, and your machine sends the final ACK, after which the connection is established and you can send and recv bytes. You normally do not call bind first — the OS automatically assigns an ephemeral source port for you. For a UDP socket, connect is optional and lighter: it does not send any packets or set up a real connection; it merely records a default destination so you can use plain send/recv instead of repeating the address in every sendto, and it filters incoming datagrams to that one peer.
Why it matters: connect is the very first thing almost every client does, so its failure modes are everyday programming reality. It can fail fast with 'connection refused' (nothing is listening on that port), or hang and then time out (the host is unreachable or a firewall is silently dropping packets). On a blocking socket, connect waits for the whole handshake before returning; on a non-blocking socket it returns immediately and you finish the connection later using select, poll, or epoll — the standard way clients open many connections at once without freezing.
A client does fd = socket(...); connect(fd, {93.184.216.34, 443}). The OS quietly picks an ephemeral source port, the three-way handshake runs, and connect returns success — now send and recv carry the conversation.
The client dials; the OS supplies the return port automatically.
'Connection refused' and 'connection timed out' mean different things: refused is a host actively saying no port is listening; timed out usually means the packets never got a reply at all (down host or a dropping firewall).