What you will learn
- What
connect()does and how to try every address a name resolves to. - What
listen()and its backlog really control. - Why
accept()returns a new socket and what happens to the listening one. - Using
connect()on a UDP socket.
The handshake in one picture
client server
socket() socket(), bind(), listen()
connect() ---- SYN -------------------> (kernel queues the connection)
<--- SYN-ACK ----------------
---- ACK -------------------> connection complete, waits in the queue
connect() returns 0 accept() returns a new fd for it
The three-way handshake is done entirely by the kernels. Your code only sees connect() return on one side and accept() return on the other.
connect(): the client side
int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen);
Returns 0 when the connection is established, or -1 with errno. Common errors:
| errno | Meaning |
|---|---|
ECONNREFUSED | The host answered, but nothing listens on that port |
ETIMEDOUT | No answer at all (host down, or a firewall silently drops packets) |
ENETUNREACH / EHOSTUNREACH | No route to that network or host |
Because a name can resolve to several addresses, loop over the results and stop at the first success:
int connect_to(const char *host, const char *port)
{
struct addrinfo hints, *res, *ai;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if (getaddrinfo(host, port, &hints, &res) != 0)
return -1;
int fd = -1;
for (ai = res; ai != NULL; ai = ai->ai_next) {
fd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
if (fd == -1)
continue;
if (connect(fd, ai->ai_addr, ai->ai_addrlen) == 0)
break;
close(fd); /* a failed socket can't be reused; make a new one */
fd = -1;
}
freeaddrinfo(res);
return fd;
}
A blocking connect() to an unreachable host can hang for over a minute. Lesson 12 shows how to put a deadline on it.
listen(): start accepting connections
int listen(int sockfd, int backlog);
listen() turns a bound stream socket into a listening socket. It no longer sends or receives data; its only job is to produce new connections.
The backlog caps how many fully established connections may wait for your program to call accept(). If the queue is full, new clients are delayed or refused. Values like 16–128 are fine for learning; busy servers use larger values (Linux silently caps it at net.core.somaxconn, which defaults to 4096 on current kernels). Passing SOMAXCONN means “the system maximum”.
Server order is always: socket() → setsockopt(SO_REUSEADDR) → bind() → listen() → loop on accept().
accept(): one new socket per client
int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);
accept() takes the next connection from the queue (blocking if it’s empty) and returns a brand-new descriptor connected to that client. The listening socket stays open and keeps accepting more.
for (;;) {
struct sockaddr_storage peer;
socklen_t peer_len = sizeof peer; /* reset every iteration */
int client = accept(listener, (struct sockaddr *)&peer, &peer_len);
if (client == -1) {
perror("accept");
continue;
}
/* talk to the client on `client`, then close(client) */
}
Pass NULL, NULL for the address arguments if you don’t care who connected.
Think of a restaurant host: the listening socket is the host at the door, and each accept() seats a guest at a new table (descriptor). The host goes straight back to the door.
connect() on a UDP socket
You can call connect() on a datagram socket too. No packets are exchanged; the kernel just remembers a default destination. Afterwards you can use send() / recv() instead of sendto() / recvfrom(), and the socket only receives datagrams from that peer. It also lets the kernel report errors like “port unreachable” back to you as ECONNREFUSED.
Key takeaways
connect()performs the TCP handshake; try eachgetaddrinfo()result and create a new socket per attempt.listen()makes a socket a connection factory; the backlog bounds the queue of finished handshakes.accept()returns a new connected socket per client; the listener keeps listening.connect()on UDP sets a default peer and enables error reporting.
Exercises
- Use
connect_to()against a port with nothing listening and printstrerror(errno). Then try an address that doesn’t respond (for example10.255.255.1) and time how long it takes to fail. - Write a server that never calls
accept(), set backlog to 1, and connect severalnc localhost PORTclients. Observe what happens withss -tn. - Make a UDP client that calls
connect()and thensend()s to a port with no listener twice. What does the secondsend()or arecv()report?
Quiz
- After
accept()returns, which socket do you use to talk to the client? - What happens if you
close()a socket after a failedconnect()and want to try the next address? - What does the backlog in
listen()limit?
Show answers
- The new descriptor returned by
accept(). The listening socket is only for accepting. - That’s correct practice: after a failed
connect()the socket’s state is unspecified, so close it and create a new socket for the next address. - The number of connections that have completed the handshake and are waiting for your program to
accept()them.