Lesson 10 of 18 Client-Server Programs

TCP Client-Server Example in C

Build a complete TCP client and server in C: a forking server that upper-cases text, a matching client, SIGCHLD reaping, and how to test it locally.

50-60 min intermediate 0/18 lessons done
Course contents Lesson 10 of 18 · 0 done
On this page (9 sections)
  1. What you will build
  2. The client-server model
  3. The server
  4. The client
  5. Run it
  6. Design notes and limits
  7. Key takeaways
  8. Exercises
  9. Quiz

What you will build

A “shout” service: clients send text and the server sends it back in UPPER CASE. It’s small enough to read in one sitting and uses every call from Module 2:

  • getaddrinfo() with AI_PASSIVE, socket(), SO_REUSEADDR, bind(), listen()
  • accept() in a loop, getnameinfo() to log the client
  • one child process per client with fork(), and zombie reaping with SIGCHLD
  • a client that loops over addresses, sends everything, half-closes with shutdown() and reads until end-of-stream

The client-server model

Almost every network service follows the same shape: a server process starts first, binds a well-known port and waits; clients connect whenever they like, make requests and leave. A web server, an SSH daemon and your shout server differ only in the protocol spoken after accept().

A server needs a way to handle several clients at once. The classic Unix answer, used here, is to fork() a child per connection. Lessons 13 and 14 show the single-process alternative with poll() and select().

The server

/* shout_server.c - TCP server that sends back each line in UPPER CASE.
 * One child process per client. Usage: ./shout_server 5050 */
#include <ctype.h>
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#define BACKLOG 16

static void reap_children(int sig)
{
    (void)sig;
    int saved = errno;                 /* waitpid may change errno */
    while (waitpid(-1, NULL, WNOHANG) > 0)
        ;
    errno = saved;
}

static int open_listener(const char *port)
{
    struct addrinfo hints, *res, *ai;
    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE;       /* wildcard address: all interfaces */

    int rc = getaddrinfo(NULL, port, &hints, &res);
    if (rc != 0) {
        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rc));
        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;
        int on = 1;
        setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof on);
        if (bind(fd, ai->ai_addr, ai->ai_addrlen) == 0)
            break;                     /* success */
        close(fd);
        fd = -1;
    }
    freeaddrinfo(res);

    if (fd == -1) {
        fprintf(stderr, "could not bind to port %s\n", port);
        return -1;
    }
    if (listen(fd, BACKLOG) == -1) {
        perror("listen");
        close(fd);
        return -1;
    }
    return fd;
}

static void serve_client(int fd)
{
    char buf[1024];
    ssize_t n;
    while ((n = recv(fd, buf, sizeof buf, 0)) > 0) {
        for (ssize_t i = 0; i < n; i++)
            buf[i] = (char)toupper((unsigned char)buf[i]);
        ssize_t sent = 0;
        while (sent < n) {             /* send() may write only part */
            ssize_t w = send(fd, buf + sent, (size_t)(n - sent), 0);
            if (w == -1) {
                perror("send");
                return;
            }
            sent += w;
        }
    }
    if (n == -1)
        perror("recv");
}

int main(int argc, char *argv[])
{
    const char *port = argc > 1 ? argv[1] : "5050";
    int listener = open_listener(port);
    if (listener == -1)
        return 1;

    struct sigaction sa;
    memset(&sa, 0, sizeof sa);
    sa.sa_handler = reap_children;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = SA_RESTART;          /* restart accept() after SIGCHLD */
    sigaction(SIGCHLD, &sa, NULL);

    printf("shout server listening on port %s\n", port);

    for (;;) {
        struct sockaddr_storage peer;
        socklen_t peer_len = sizeof peer;
        int client = accept(listener, (struct sockaddr *)&peer, &peer_len);
        if (client == -1) {
            perror("accept");
            continue;
        }

        char host[NI_MAXHOST], serv[NI_MAXSERV];
        if (getnameinfo((struct sockaddr *)&peer, peer_len, host, sizeof host,
                        serv, sizeof serv, NI_NUMERICHOST | NI_NUMERICSERV) == 0)
            printf("client connected from %s port %s\n", host, serv);

        pid_t pid = fork();
        if (pid == 0) {                /* child */
            close(listener);           /* child doesn't accept */
            serve_client(client);
            close(client);
            _exit(0);
        }
        if (pid == -1)
            perror("fork");
        close(client);                 /* parent doesn't talk to the client */
    }
}

Walking through it

open_listener() is the standard server setup from lessons 5–7. It tries each getaddrinfo() result until one binds. On most Linux systems the first result is IPv4 (0.0.0.0); see the exercises for serving IPv4 and IPv6 at once.

The accept loop. Each accept() returns a new descriptor. We log the peer with getnameinfo() and NI_NUMERICHOST, then fork.

Parent and child each close what they don’t need. After fork() both processes hold both descriptors. The child closes the listener (it will never accept), the parent closes the client socket (the child handles it). Forgetting the parent’s close(client) leaks one descriptor per connection and the client never sees end-of-stream.

serve_client() reads whatever arrives, transforms it, and writes it back with a loop, because send() may write only part of the buffer.

Reaping children. A child that exits becomes a zombie until its parent collects its exit status. Our SIGCHLD handler calls waitpid(-1, NULL, WNOHANG) in a loop (several children can exit while one signal is pending). It saves and restores errno because it can interrupt code that’s about to check errno. SA_RESTART makes the interrupted accept() resume automatically instead of failing with EINTR.

_exit() in the child skips flushing stdio buffers inherited from the parent, which would otherwise print duplicate output.

The client

/* shout_client.c - send one message to the shout server and print the reply.
 * Usage: ./shout_client localhost 5050 "hello there" */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>

static 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;

    int rc = getaddrinfo(host, port, &hints, &res);
    if (rc != 0) {
        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rc));
        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;                     /* connected */
        close(fd);
        fd = -1;
    }
    freeaddrinfo(res);
    return fd;
}

int main(int argc, char *argv[])
{
    if (argc != 4) {
        fprintf(stderr, "usage: %s host port message\n", argv[0]);
        return 1;
    }

    int fd = connect_to(argv[1], argv[2]);
    if (fd == -1) {
        fprintf(stderr, "could not connect to %s:%s\n", argv[1], argv[2]);
        return 2;
    }

    size_t len = strlen(argv[3]);
    size_t sent = 0;
    while (sent < len) {
        ssize_t w = send(fd, argv[3] + sent, len - sent, 0);
        if (w == -1) {
            perror("send");
            close(fd);
            return 3;
        }
        sent += (size_t)w;
    }
    shutdown(fd, SHUT_WR);             /* tell the server we're done sending */

    char buf[512];
    ssize_t n;
    while ((n = recv(fd, buf, sizeof buf, 0)) > 0)
        fwrite(buf, 1, (size_t)n, stdout);
    putchar('\n');

    close(fd);
    return 0;
}

The client resolves the host, tries each address until connect() succeeds, sends the message with a loop, then calls shutdown(fd, SHUT_WR). That makes the server’s recv() return 0, so the server’s loop ends and the child closes the socket, which in turn makes the client’s recv() return 0. A clean, deterministic finish with no “magic” end marker.

Run it

Compile both and run them in two terminals:

gcc -Wall -Wextra -o shout_server shout_server.c
gcc -Wall -Wextra -o shout_client shout_client.c

./shout_server 5050
# in another terminal
./shout_client localhost 5050 "hello sockets"
HELLO SOCKETS

The server prints a line like client connected from 127.0.0.1 port 51734. You can also talk to it interactively with nc localhost 5050 or telnet localhost 5050: every line you type comes back shouted.

You only need one computer. Loopback (localhost, 127.0.0.1, ::1) behaves like a real network for everything in this course.

Design notes and limits

  • One process per client is simple and isolates clients from each other’s crashes, but each process costs memory. Thousands of clients call for poll()/epoll or threads.
  • The protocol has no message framing: the server transforms whatever bytes arrive, which works only because upper-casing doesn’t care where chunks split. Real protocols need framing.
  • There’s no timeout: a client that connects and goes silent keeps a child busy forever. Lesson 12 fixes that.

Key takeaways

  • The canonical server is: resolve, socket, SO_REUSEADDR, bind, listen, accept loop.
  • After fork(), the child closes the listener and the parent closes the client socket.
  • Reap children with a SIGCHLD handler that loops on waitpid(..., WNOHANG).
  • A client can signal “request complete” with shutdown(SHUT_WR) and still read the reply.

Exercises

  1. Add a per-client counter: the server sends you are client #N when each client connects. (Hint: the parent increments the counter before fork().)
  2. Make the server listen on IPv6 and IPv4 at the same time with a single AF_INET6 socket and IPV6_V6ONLY set to 0. Test with -4 and -6 options of nc.
  3. Replace upper-casing with a tiny command protocol: TIME returns the server’s time, ECHO text echoes, anything else returns ERR. Process input line by line.

Quiz

  1. Why must the parent call close(client) after fork()?
  2. What would happen to finished children without the SIGCHLD handler?
  3. How does the shout client tell the server that its message is complete?
Show answers
  1. Otherwise the parent leaks a descriptor per client, and the connection never fully closes when the child finishes because the parent still holds a reference.
  2. They’d remain as zombie processes, holding process-table entries until the parent exits.
  3. It calls shutdown(fd, SHUT_WR), so the server’s recv() returns 0 after the last byte.

Finished this lesson?

Mark it complete to track your progress (saved in this browser).