Build a portable TCP client in C

8 steps · about 2 h 8 min · Intermediate

  1. 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.

  2. 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.

  3. Create each candidate socket (reference, Linux man-pages, 14 min)

    The socket contract clarifies file descriptors, types and the errors that belong in diagnostics.

  4. 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.

  5. Loop until the request is sent (reference, Linux man-pages, 16 min)

    send may transfer fewer bytes than requested and may be interrupted.

  6. 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.

  7. 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.

  8. 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.