C Academy · Lesson

TCP Client

Connect and send.

Lesson 3 of 413 steps

TCP Client is a free C Academy lesson on CoddyKit. This is lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C Academy learning path, and your progress syncs across the web and the CoddyKit app. The C Academy course includes 4 lessons in total.

Building a TCP Client

A TCP client connects to a server, then sends and receives data. Its lifecycle is shorter than the server's: create a socket, connect, communicate, and close.

Step 1: Create the Socket

Just like the server, create a stream socket for IPv4 TCP.

#include <sys/socket.h>
#include <stdio.h>

int make_client_socket(void) {
    int fd = socket(AF_INET, SOCK_STREAM, 0);
    if (fd < 0) perror("socket");
    return fd;
}

Step 2: Describe the Server

Fill a sockaddr_in with the server's port and IP. Use inet_pton to convert the dotted IP string into binary form.

#include <arpa/inet.h>
#include <netinet/in.h>

int set_server(struct sockaddr_in *addr, const char *ip, unsigned short port) {
    addr->sin_family = AF_INET;
    addr->sin_port = htons(port);
    return inet_pton(AF_INET, ip, &addr->sin_addr); /* 1 on success */
}

Step 3: Connect

connect() performs the TCP handshake with the server. On success the socket is ready for data; on failure it sets errno (for example connection refused).

#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>

int do_connect(int fd, struct sockaddr_in *addr) {
    if (connect(fd, (struct sockaddr *)addr, sizeof *addr) < 0) {
        perror("connect"); return -1;
    }
    return 0;
}

No Bind Needed

Clients usually skip bind: the kernel assigns an ephemeral source port automatically during connect. You only bind a client when you need a specific source port.

Step 4: Send Data

After connecting, write a request with send. Loop to ensure the whole buffer goes out.

#include <sys/socket.h>
#include <string.h>

int send_all(int fd, const char *data) {
    size_t left = strlen(data);
    const char *p = data;
    while (left > 0) {
        ssize_t n = send(fd, p, left, 0);
        if (n <= 0) return -1;
        p += n; left -= (size_t)n;
    }
    return 0;
}

Step 5: Receive the Reply

Read the server's response with recv. Null-terminate before treating the buffer as a string.

#include <sys/socket.h>
#include <stdio.h>

void read_reply(int fd) {
    char buf[512];
    ssize_t n = recv(fd, buf, sizeof buf - 1, 0);
    if (n > 0) { buf[n] = 0; printf("server said: %s\n", buf); }
    else if (n == 0) printf("server closed connection\n");
}

Reading Until Closed

One recv may not return the full response. Loop until recv returns 0 (peer closed) to read an entire reply that arrives in pieces.

#include <sys/socket.h>
#include <stdio.h>

void drain(int fd) {
    char buf[256]; ssize_t n;
    while ((n = recv(fd, buf, sizeof buf, 0)) > 0)
        fwrite(buf, 1, (size_t)n, stdout);
}

Step 6: Close

Call close(fd) to end the connection and free the descriptor. This sends a TCP FIN so the server learns the client is done.

#include <unistd.h>

void finish(int fd) {
    close(fd);
}

Half-Close With shutdown

shutdown(fd, SHUT_WR) closes only the write direction, signaling end-of-request while still allowing the client to read the reply. This is useful for request-then-response protocols.

Handling Connection Failures

Common client errors: ECONNREFUSED (no server listening), ETIMEDOUT (host unreachable), and EHOSTUNREACH. Always check connect and report failures clearly to the user.

Quick Check

Test your understanding of TCP clients.

Recap

You built a TCP client.

  • socket, then connect to the server's sockaddr_in
  • No bind needed; the kernel picks a source port
  • send the request, recv the reply (loop for full data)
  • close or shutdown when done; handle connect failures
Free to start

Learn C with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
39
Lessons
144

Frequently Asked Questions

Is the “TCP Client” lesson free?

Yes — the full text of “TCP Client” is free to read here on the web. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C Academy course, upgrade to CoddyKit PRO. The C Academy course includes 4 lessons in total.

What will I learn in “TCP Client”?

Connect and send. You practise C Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start C Academy?

No prior experience is required. C Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 3 of 4.

How long does the “TCP Client” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this C Academy lesson?

Yes. Every C Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Sockets Overview
  2. TCP Server
  3. TCP Client
  4. Handling Multiple Clients
← Back to C Academy