Networking & IoT · Interview question

Walk through the socket calls for a TCP client and a TCP server.

A strong answer

A client creates a socket with socket(AF_INET, SOCK_STREAM, 0) for TCP, fills in a sockaddr_in with the server's IP and port (port converted with htons), then calls connect(), which performs the three-way handshake; once connected it exchanges data with send()/recv() and calls close() when done. A server creates a socket, calls bind() to claim a local IP and port, listen() to mark it as accepting connections and set a backlog, then accept() which blocks until a client connects and returns a new socket dedicated to that client (the original listening socket keeps accepting more); it then uses send/recv on the per-client socket and closes it when the conversation ends. The key subtlety people miss is that accept() returns a separate connected socket per client, so the server can keep listening on the original while servicing accepted ones (often one per thread/task, or multiplexed with select). UDP skips connect/listen/accept entirely: create a SOCK_DGRAM socket, optionally bind() a local port, and use sendto/recvfrom with the peer address on each call.

What a weak answer sounds like

You know the answer. Do you know what gets you dinged?

Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.

From the lesson

Sockets

The programming interface to TCP/UDP: the BSD socket calls (socket/connect/send/recv, bind/listen/accept), client and server flows, byte order, and the partial-I/O and blocking traps on an MCU.

More Sockets questions

Browse all 472 interview questions
Walk through the socket calls for a TCP client and a TCP server. | EmbeddedPrep.io