Build a portable TCP client in C
8 steps · about 2 h 8 min · Intermediate
- Map sockets onto the TCP layer (reference, Linux man-pages, 16 min)
The protocol overview supplies the stream and connection concepts used by every later call.
- Resolve a host into candidate addresses (reference, Linux man-pages, 20 min)
getaddrinfo supports protocol-independent resolution and returns a list that must be tried and freed correctly.
- Create each candidate socket (reference, Linux man-pages, 14 min)
The socket contract clarifies file descriptors, types and the errors that belong in diagnostics.
- Connect with explicit failure handling (reference, Linux man-pages, 16 min)
A client must distinguish a failed candidate from the end of all viable addresses.
- Loop until the request is sent (reference, Linux man-pages, 16 min)
send may transfer fewer bytes than requested and may be interrupted.
- Read a bounded response correctly (reference, Linux man-pages, 16 min)
recv distinguishes available bytes, orderly shutdown and errors that a robust loop must preserve.
- Bound waiting with poll (reference, Linux man-pages, 18 min)
poll adds a visible timeout instead of letting a failed peer block the program forever.
- Report and clean up every failure path (reference, Linux man-pages, 12 min)
Useful system-error text plus one cleanup path makes failures diagnosable without leaking resources.