Skip to content

Sockets in Network Communication

This section contains examples related to the use of sockets for network communication in C. Below is a list of the source files with links to their content.

File Name Description Link
rotn_server.c A concurrent TCP server on port PORT (5001 by default) that sends back each received line obfuscated with ROT3; stops with an error message if the socket cannot be created View
test_sockets.c Opens 8 sockets (Unix/Internet, stream/datagram/raw) and waits for Ctrl-C, to observe them with lsof -p <PID>; raw sockets need root View
testbind1.c Demonstrates creating and binding a TCP/IP stream socket (optional port between 1 and 65535) View
testbind2.c Demonstrates creating and binding a TCP/IP stream socket to a specific host (resolved with getaddrinfo(), port 5001) View
resolve_name.c Demonstrates resolving a hostname to its IP address(es) using getaddrinfo() (formerly testgethostbyname.c: gethostbyname() is obsolete) View
echo_server_iterative.c Running example: iterative TCP echo server on port 5001 (course, chapter "Sockets") View
echo_server_concurrent.c Running example: concurrent TCP echo server (one child per client, children reaped on SIGCHLD) (course, chapter "Sockets") View
echo_server_poll.c TCP echo server serving all its clients in a single process with poll() (course, chapter "Sockets") View
echo_client.c Running example: TCP client of the echo server, reads each echo up to the end of line (course, chapter "Sockets") View
udp_echo_server.c Running example: UDP echo receiver on port 5001 (course, chapter "Sockets") View
udp_echo_client.c Running example: UDP sender that sends a datagram and displays its echo (course, chapter "Sockets") View

Sources

src/echo_client.c

View on GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>      /* fgets(), printf(), fprintf(), perror() */
#include <stdlib.h>     /* exit() */
#include <string.h>     /* memset(), strlen() */
#include <signal.h>     /* signal(), SIGPIPE */
#include <unistd.h>     /* read(), write(), close() */
#include <arpa/inet.h>  /* htons(), inet_pton() */
#include <netinet/in.h> /* struct sockaddr_in */
#include <sys/socket.h> /* socket(), connect() */

/**
 * @file echo_client.c
 * @brief Running example: TCP client of the echo server (port 5001).
 *
 * Lecture: chapter os-11 "Sockets" ("Fil rouge - client (1/2)" and
 * "(2/2)", "Lire une ligne : lire_ligne()" in the appendices).
 *
 * The client sends each line read on the standard input to the server,
 * reads the echo up to '\n' and displays it. Ctrl-D closes the connection:
 * the server reads EOF.
 *
 * Key points:
 *   - the answer is read up to '\n', not in a single read(): TCP is a byte
 *     stream;
 *   - lire_ligne() makes one system call per byte: simple, but slow;
 *   - with a host name rather than an address, use getaddrinfo() (slide
 *     "getaddrinfo() - essayer chaque adresse").
 * The port can be changed at compile time: -DPORT=5002.
 *
 * \code{.bash}
 *   $ ./echo_client 127.0.0.1
 *   bonjour
 *   écho : bonjour
 *   ^D
 * \endcode
 */

#ifndef PORT
#define PORT 5001
#endif

/**
 * @brief Displays the error message (perror), then exits.
 */
void erreur(const char *msg) {
    perror(msg);
    exit(EXIT_FAILURE);
}

/**
 * @brief Writes the n bytes of buf.
 * @return n, or -1 on error.
 */
ssize_t ecrire_n(int fd, const char *buf, size_t n) {
    size_t fait = 0;
    while (fait < n) {
        ssize_t r = write(fd, buf + fait, n - fait);
        if (r == -1) {
            return -1;
        }
        fait += r;
    }
    return fait;
}

/**
 * @brief Reads up to '\n' included.
 * @return The length of the line, 0 on immediate EOF.
 */
size_t lire_ligne(int fd, char *buf, size_t max) {
    size_t i = 0;
    char c;
    while (i < max - 1) {
        if (read(fd, &c, 1) != 1) {
            break;             /* EOF or error */
        }
        buf[i++] = c;
        if (c == '\n') {
            break;
        }
    }
    buf[i] = '\0';
    return i;
}

int main(int argc, char *argv[]) {
    struct sockaddr_in srv;
    char ligne[512];

    if (argc != 2) {
        fprintf(stderr, "usage : %s ip\n", argv[0]);
        exit(EXIT_FAILURE);
    }
    int fd = socket(AF_INET, SOCK_STREAM, 0);
    if (fd == -1) {
        erreur("socket");
    }
    memset(&srv, 0, sizeof srv);
    srv.sin_family = AF_INET;
    srv.sin_port = htons(PORT);
    if (inet_pton(AF_INET, argv[1], &srv.sin_addr) != 1) {
        fprintf(stderr, "adresse invalide\n");
        exit(EXIT_FAILURE);
    }
    if (connect(fd, (struct sockaddr *) &srv, sizeof srv) == -1) {
        erreur("connect");
    }
    signal(SIGPIPE, SIG_IGN);      /* server left: EPIPE */

    while (fgets(ligne, sizeof ligne, stdin) != NULL) {
        if (ecrire_n(fd, ligne, strlen(ligne)) == -1) {
            break;                 /* server left */
        }
        if (lire_ligne(fd, ligne, sizeof ligne) == 0) {
            break;                 /* server left */
        }
        printf("écho : %s", ligne);
    }
    close(fd);                     /* EOF for the server */

    return EXIT_SUCCESS;
}
src/echo_server_concurrent.c

View on GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>      /* perror() */
#include <stdlib.h>     /* exit() */
#include <string.h>     /* memset() */
#include <errno.h>      /* errno */
#include <signal.h>     /* sigaction(), signal(), SIGCHLD, SIGPIPE */
#include <stdint.h>     /* uint16_t */
#include <unistd.h>     /* read(), write(), close(), fork() */
#include <arpa/inet.h>  /* htons(), htonl() */
#include <netinet/in.h> /* struct sockaddr_in, INADDR_ANY */
#include <sys/socket.h> /* socket(), bind(), listen(), accept(), setsockopt() */
#include <sys/wait.h>   /* waitpid(), WNOHANG */

/**
 * @file echo_server_concurrent.c
 * @brief Running example: concurrent TCP echo server on port 5001, one
 * child process per client.
 *
 * Lecture: chapter os-11 "Sockets" ("Fil rouge - serveur concurrent",
 * "Récolter les enfants : SIGCHLD", "SO_REUSEADDR").
 *
 * The parent (the "veilleur") only accepts connections; each client is
 * served by a child process.
 *
 * Key points:
 *   - the child closes the listening socket, the parent closes the
 *     communication socket; otherwise the connection would not be closed
 *     when the client leaves;
 *   - the children are reaped in a SIGCHLD handler, with waitpid(-1, NULL,
 *     WNOHANG) in a loop, otherwise they would remain zombies;
 *   - SA_RESTART restarts accept() interrupted by the signal.
 * The port can be changed at compile time: -DPORT=5002.
 *
 * \code{.bash}
 *   $ ./echo_server_concurrent &
 *   $ nc 127.0.0.1 5001        # several clients at the same time
 *   salut
 *   salut
 * \endcode
 */

#ifndef PORT
#define PORT 5001
#endif

/**
 * @brief Displays the error message (perror), then exits.
 */
void erreur(const char *msg) {
    perror(msg);
    exit(EXIT_FAILURE);
}

/**
 * @brief Writes the n bytes of buf.
 * @return n, or -1 on error.
 */
ssize_t ecrire_n(int fd, const char *buf, size_t n) {
    size_t fait = 0;
    while (fait < n) {
        ssize_t r = write(fd, buf + fait, n - fait);
        if (r == -1) {
            return -1;
        }
        fait += r;
    }
    return fait;
}

/**
 * @brief Sends back to the client everything it sends, until it closes
 * the connection.
 */
void servir(int com) {
    char buf[512];
    ssize_t n;
    while ((n = read(com, buf, sizeof buf)) > 0) {
        if (ecrire_n(com, buf, n) == -1) {
            break;             /* client left */
        }
    }
}

/**
 * @brief Creates the listening socket; exits on error.
 */
int creer_ecoute(uint16_t port) {
    struct sockaddr_in adr;
    int oui = 1;
    int ecoute = socket(AF_INET, SOCK_STREAM, 0);
    if (ecoute == -1) {
        erreur("socket");
    }
    if (setsockopt(ecoute, SOL_SOCKET, SO_REUSEADDR,
                   &oui, sizeof oui) == -1) {
        erreur("setsockopt");
    }
    memset(&adr, 0, sizeof adr);
    adr.sin_family = AF_INET;
    adr.sin_port = htons(port);
    adr.sin_addr.s_addr = htonl(INADDR_ANY);
    if (bind(ecoute, (struct sockaddr *) &adr, sizeof adr) == -1) {
        erreur("bind");
    }
    if (listen(ecoute, 10) == -1) {
        erreur("listen");
    }
    return ecoute;
}

/**
 * @brief SIGCHLD handler: reaps every finished child.
 */
void sur_sigchld(int sig) {
    int sauve = errno;         /* waitpid() modifies errno */
    (void) sig;
    while (waitpid(-1, NULL, WNOHANG) > 0) {
        ;                      /* each finished child */
    }
    errno = sauve;
}

int main(void) {
    struct sigaction sa;

    memset(&sa, 0, sizeof sa);
    sa.sa_handler = sur_sigchld;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = SA_RESTART;      /* restart accept() */
    if (sigaction(SIGCHLD, &sa, NULL) == -1) {
        erreur("sigaction");
    }
    signal(SIGPIPE, SIG_IGN);      /* EPIPE */

    int ecoute = creer_ecoute(PORT);
    for (;;) {
        int com = accept(ecoute, NULL, NULL);
        if (com == -1) {
            if (errno != EINTR) {  /* EINTR: interrupted by SIGCHLD, not an error */
                perror("accept");
            }
            continue;
        }
        pid_t pid = fork();
        if (pid == -1) {
            perror("fork");
        } else if (pid == 0) {     /* child */
            close(ecoute);         /* does not accept */
            servir(com);
            close(com);
            exit(EXIT_SUCCESS);
        }
        close(com);                /* parent */
    }
}
src/echo_server_iterative.c

View on GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>      /* printf(), perror() */
#include <stdlib.h>     /* exit() */
#include <string.h>     /* memset() */
#include <signal.h>     /* signal(), SIGPIPE */
#include <stdint.h>     /* uint16_t */
#include <unistd.h>     /* read(), write(), close() */
#include <arpa/inet.h>  /* htons(), htonl(), ntohs(), inet_ntop() */
#include <netinet/in.h> /* struct sockaddr_in, INADDR_ANY */
#include <sys/socket.h> /* socket(), bind(), listen(), accept(), setsockopt() */

/**
 * @file echo_server_iterative.c
 * @brief Running example: iterative TCP echo server on port 5001.
 *
 * Lecture: chapter os-11 "Sockets" ("Fil rouge - servir un client",
 * "Fil rouge - socket d'écoute", "Fil rouge - serveur itératif").
 *
 * The server sends back to the client everything it receives, until the
 * client closes the connection, then accepts the next client.
 *
 * Key points:
 *   - listening socket != communication socket;
 *   - TCP is a byte stream: write() may write less than requested, hence
 *     ecrire_n();
 *   - SIGPIPE is ignored: writing to a client that left gives EPIPE;
 *   - SO_REUSEADDR (slide "SO_REUSEADDR") allows restarting the server
 *     despite connections in TIME_WAIT;
 *   - limit: while servir() runs, a second client is not served (see
 *     echo_server_concurrent.c).
 * The port can be changed at compile time: -DPORT=5002 (default 5001:
 * on macOS, port 5000 is used by the AirPlay receiver).
 *
 * \code{.bash}
 *   $ ./echo_server_iterative          # terminal 1
 *   client 127.0.0.1:48512
 *   $ nc 127.0.0.1 5001                # terminal 2 (or echo_client)
 *   salut
 *   salut
 * \endcode
 */

#ifndef PORT
#define PORT 5001
#endif

/**
 * @brief Displays the error message (perror), then exits.
 */
void erreur(const char *msg) {
    perror(msg);
    exit(EXIT_FAILURE);
}

/**
 * @brief Writes the n bytes of buf.
 * @return n, or -1 on error.
 */
ssize_t ecrire_n(int fd, const char *buf, size_t n) {
    size_t fait = 0;
    while (fait < n) {
        ssize_t r = write(fd, buf + fait, n - fait);
        if (r == -1) {
            return -1;
        }
        fait += r;
    }
    return fait;
}

/**
 * @brief Sends back to the client everything it sends, until it closes
 * the connection.
 */
void servir(int com) {
    char buf[512];
    ssize_t n;
    while ((n = read(com, buf, sizeof buf)) > 0) {
        if (ecrire_n(com, buf, n) == -1) {
            break;             /* client left */
        }
    }
    if (n == -1) {
        perror("read");
    }
}

/**
 * @brief Creates the listening socket; exits on error.
 */
int creer_ecoute(uint16_t port) {
    struct sockaddr_in adr;
    int oui = 1;
    int ecoute = socket(AF_INET, SOCK_STREAM, 0);
    if (ecoute == -1) {
        erreur("socket");
    }
    if (setsockopt(ecoute, SOL_SOCKET, SO_REUSEADDR,
                   &oui, sizeof oui) == -1) {
        erreur("setsockopt");
    }
    memset(&adr, 0, sizeof adr);
    adr.sin_family = AF_INET;
    adr.sin_port = htons(port);
    adr.sin_addr.s_addr = htonl(INADDR_ANY);
    if (bind(ecoute, (struct sockaddr *) &adr, sizeof adr) == -1) {
        erreur("bind");
    }
    if (listen(ecoute, 10) == -1) {
        erreur("listen");
    }
    return ecoute;
}

int main(void) {
    int ecoute = creer_ecoute(PORT);
    signal(SIGPIPE, SIG_IGN);      /* EPIPE */
    for (;;) {
        struct sockaddr_in cli;
        socklen_t lg = sizeof cli;
        char ip[INET_ADDRSTRLEN];
        int com = accept(ecoute, (struct sockaddr *) &cli, &lg);
        if (com == -1) {
            /* As in the slide, the server stops; a real server would go on
               after a transient error such as ECONNABORTED */
            erreur("accept");
        }
        inet_ntop(AF_INET, &cli.sin_addr, ip, sizeof ip);
        printf("client %s:%d\n", ip, ntohs(cli.sin_port));
        fflush(stdout);
        servir(com);
        close(com);
    }
}
src/echo_server_poll.c

View on GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>      /* printf(), perror() */
#include <stdlib.h>     /* exit() */
#include <string.h>     /* memset() */
#include <errno.h>      /* errno, EINTR */
#include <poll.h>       /* poll(), struct pollfd, POLLIN, POLLHUP */
#include <signal.h>     /* signal(), SIGPIPE */
#include <stdint.h>     /* uint16_t */
#include <unistd.h>     /* read(), write(), close() */
#include <arpa/inet.h>  /* htons(), htonl() */
#include <netinet/in.h> /* struct sockaddr_in, INADDR_ANY */
#include <sys/socket.h> /* socket(), bind(), listen(), accept(), setsockopt() */

/**
 * @file echo_server_poll.c
 * @brief TCP echo server on port 5001 multiplexing all its clients with
 * poll(), in a single process.
 *
 * Lecture: chapter os-11 "Sockets" ("Multiplexer les requêtes" and, in
 * the appendices, "Multiplexer les requêtes : squelette"); see also
 * chapter os-07 "Multiplexage des entrées/sorties".
 *
 * Element 0 of the pollfd array is the listening socket: it is ready for
 * reading when a connection waits for accept(). The other elements are the
 * communication sockets: ready when the client has sent data, or closed.
 *
 * Key points:
 *   - no process to create nor to reap;
 *   - but a long processing blocks all the clients;
 *   - a client at EOF is removed from the array (the last element takes
 *     its place, hence i-- to examine it).
 * The port can be changed at compile time: -DPORT=5002.
 *
 * \code{.bash}
 *   $ ./echo_server_poll &
 *   $ nc 127.0.0.1 5001        # several clients at the same time
 *   salut
 *   salut
 * \endcode
 */

#ifndef PORT
#define PORT 5001
#endif

#define MAX 64                  /* listening socket + 63 clients */

/**
 * @brief Displays the error message (perror), then exits.
 */
void erreur(const char *msg) {
    perror(msg);
    exit(EXIT_FAILURE);
}

/**
 * @brief Writes the n bytes of buf.
 * @return n, or -1 on error.
 */
ssize_t ecrire_n(int fd, const char *buf, size_t n) {
    size_t fait = 0;
    while (fait < n) {
        ssize_t r = write(fd, buf + fait, n - fait);
        if (r == -1) {
            return -1;
        }
        fait += r;
    }
    return fait;
}

/**
 * @brief Creates the listening socket; exits on error.
 */
int creer_ecoute(uint16_t port) {
    struct sockaddr_in adr;
    int oui = 1;
    int ecoute = socket(AF_INET, SOCK_STREAM, 0);
    if (ecoute == -1) {
        erreur("socket");
    }
    if (setsockopt(ecoute, SOL_SOCKET, SO_REUSEADDR,
                   &oui, sizeof oui) == -1) {
        erreur("setsockopt");
    }
    memset(&adr, 0, sizeof adr);
    adr.sin_family = AF_INET;
    adr.sin_port = htons(port);
    adr.sin_addr.s_addr = htonl(INADDR_ANY);
    if (bind(ecoute, (struct sockaddr *) &adr, sizeof adr) == -1) {
        erreur("bind");
    }
    if (listen(ecoute, 10) == -1) {
        erreur("listen");
    }
    return ecoute;
}

/**
 * @brief Adds the communication socket com to the array (closes it if the
 * array is full or if accept() failed).
 */
void ajouter(struct pollfd fds[], int *nb, int com) {
    if (com == -1) {
        return;
    }
    if (*nb == MAX) {
        close(com);             /* too many clients */
        return;
    }
    fds[*nb].fd = com;
    fds[*nb].events = POLLIN;
    fds[*nb].revents = 0;
    (*nb)++;
}

/**
 * @brief Closes the socket of element i and replaces it by the last one.
 */
void retirer(struct pollfd fds[], int *nb, int i) {
    close(fds[i].fd);
    fds[i] = fds[*nb - 1];
    (*nb)--;
}

/**
 * @brief One read(), then sends back what was read.
 * @return The result of read(): 0 on EOF, -1 on error.
 */
ssize_t echo_une_fois(int fd) {
    char buf[512];
    ssize_t n = read(fd, buf, sizeof buf);
    if (n > 0 && ecrire_n(fd, buf, n) == -1) {
        return -1;              /* client left */
    }
    return n;
}

int main(void) {
    int ecoute = creer_ecoute(PORT);
    signal(SIGPIPE, SIG_IGN);           /* EPIPE */

    struct pollfd fds[MAX] = {
        { .fd = ecoute, .events = POLLIN, .revents = 0 },
    };
    int nb = 1;

    for (;;) {
        if (poll(fds, nb, -1) == -1) {
            if (errno == EINTR) {
                continue;
            }
            erreur("poll");
        }
        if (fds[0].revents & POLLIN) {      /* new client */
            ajouter(fds, &nb, accept(ecoute, NULL, NULL));
        }
        for (int i = 1; i < nb; i++) {
            if (fds[i].revents & (POLLERR | POLLNVAL)) {  /* error: no read */
                retirer(fds, &nb, i--);
                continue;
            }
            if (fds[i].revents & (POLLIN | POLLHUP)) {
                if (echo_une_fois(fds[i].fd) <= 0) {
                    retirer(fds, &nb, i--);  /* EOF */
                }
            }
        }
    }
}
src/resolve_name.c

View on GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#define _POSIX_C_SOURCE 200809L
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

/**
 * @file resolve_name.c
 * @brief Demonstrates resolving a hostname to its IP address(es) using
 * getaddrinfo().
 *
 * This program takes a hostname as a command line argument and resolves it
 * to its corresponding IP address(es). It replaces the historical
 * gethostbyname() + inet_ntoa() version: gethostbyname() only handles IPv4,
 * is not reentrant and was removed from POSIX in 2008; getaddrinfo() and
 * inet_ntop() handle IPv4 and IPv6.
 *
 * \code{.bash}
 *   $ ./resolve_name localhost
 *   localhost addresses: ::1 127.0.0.1
 * \endcode
 */

/**
 * @brief Resolves the given hostname and prints its IP address(es).
 * 
 * @param hostname The hostname to resolve.
 */
void resolve_and_print(const char *hostname) {
    struct addrinfo hints;
    struct addrinfo *res;
    struct addrinfo *p;
    char ipstr[INET6_ADDRSTRLEN];
    int status;

    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC; /* AF_INET or AF_INET6 to force version */
    hints.ai_socktype = SOCK_STREAM;

    if ((status = getaddrinfo(hostname, NULL, &hints, &res)) != 0) {
        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(status));
        exit(EXIT_FAILURE);
    }

    printf("%s addresses: ", hostname);
    for (p = res; p != NULL; p = p->ai_next) {
        void *address = NULL;
        if (p->ai_family == AF_INET) { /* IPv4 */
            struct sockaddr_in *ipv4 = (struct sockaddr_in *) p->ai_addr;
            address = &(ipv4->sin_addr);
        } else { /* IPv6 */
            struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *) p->ai_addr;
            address = &(ipv6->sin6_addr);
        }

        /* Convert the IP to a string and print it: */
        inet_ntop(p->ai_family, address, ipstr, sizeof ipstr);
        printf("%s ", ipstr);
    }
    printf("\n");

    freeaddrinfo(res); /* Free the linked list */
}

int main(int argc, char **argv) {
    if (argc < 2) {
        fprintf(stderr, "Usage: %s hostname\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    resolve_and_print(argv[1]);

    return EXIT_SUCCESS;
}
src/rotn_server.c

View on GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#define _POSIX_C_SOURCE 200809L
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <signal.h>
#include <netinet/in.h> /* Internet structures and functions. */
#include <arpa/inet.h>  /* htons(), htonl() */
#include <sys/socket.h> /* Socket functions. */
#include <sys/wait.h>

/**
 * @file rotn_server.c
 * @brief A TCP server that performs ROTn obfuscation on received text.
 *
 * This server listens for TCP connections on port 5001. For each incoming
 * connection, it forks a new process to handle the connection. It reads data
 * from the connection, applies ROTn obfuscation, and sends the result back.
 * The server also handles SIGCHLD signals to prevent zombie processes.
 */

#define MAX_LINE 16384
#ifndef PORT
#define PORT 5001
#endif

static int send_all(int fd, const char *buffer, size_t len) {
    size_t total_sent = 0;

    while (total_sent < len) {
        ssize_t sent = send(fd, buffer + total_sent, len - total_sent, 0);
        if (sent < 0) {
            if (errno == EINTR) {
                continue;
            }
            return -1;
        }
        if (sent == 0) {
            return -1;
        }
        total_sent += (size_t) sent;
    }

    return 0;
}

/**
 * @brief Apply ROTn obfuscation to a character.
 * 
 * @param c Character to obfuscate.
 * @param rot Number of positions to rotate.
 * @return char The obfuscated character.
 */
char rot_char(char c, int rot) {
    char result;

    /* rotation modulo 26 (the former "+rot for a-m, -rot for n-z" was
     * only correct for rot = 13) */
    result = c;
    if (c >= 'a' && c <= 'z') {
        result = (char) ('a' + (c - 'a' + rot) % 26);
    } else if (c >= 'A' && c <= 'Z') {
        result = (char) ('A' + (c - 'A' + rot) % 26);
    }

    return result;
}

/**
 * @brief Signal handler for SIGCHLD.
 *
 * Cleans up zombie processes created by finished child processes.
 *
 * @param sig Signal number (not used).
 */
void sigchld_handler(int sig) {
    int saved_errno = errno;   /* waitpid() modifies errno */
    (void) sig;
    /* Wait for all dead processes. */
    /* We use a non-blocking call to avoid hanging if a child hasn't exited yet. */
    while (waitpid(-1, NULL, WNOHANG) > 0);
    errno = saved_errno;
}

/**
 * @brief Handles a single client connection.
 * 
 * Reads data from the client, applies ROTn obfuscation, and sends it back.
 * Closes the socket once the communication is done.
 *
 * @param fd File descriptor for the client socket.
 */
void handle_child(int fd) {
    char outbuf[MAX_LINE + 1];
    size_t outbuf_used;
    ssize_t result;

    outbuf_used = 0;

    while (1) {
        char ch;

        /* Read each character from the client */
        result = recv(fd, &ch, 1, 0);
        if (result == 0) {
            break;
        } else if (result == -1) {
            perror("recv");
            break;
        }

        outbuf[outbuf_used++] = rot_char(ch, 3);

        /* Send at the end of a line, or when the buffer is full (very long
           line): no character is lost, the '\n' included */
        if (ch == '\n' || outbuf_used == sizeof(outbuf)) {
            /* Send message to the socket of the incoming connection */
            if (send_all(fd, outbuf, outbuf_used) == -1) {
                perror("send");
                break;
            }
            outbuf_used = 0;
        }
    }

    close(fd);  /* Close the client socket */
}

/**
 * @brief Sets up and runs the ROTn server.
 *
 * Initializes the server socket, listens for incoming connections,
 * and handles them by forking new processes.
 */
void run(void) {
    int listener;
    int yes = 1;
    struct sockaddr_in sin;
    struct sigaction sa;

    /* SECURITY NOTE: this demo server has no authentication, encryption, or rate limiting.
     * Production services need TLS, access control, timeouts, and DoS protections. */
    /*---- Configure settings of the server address struct ----*/
    memset(&sin, 0, sizeof(sin));
    /* Address family = Internet */
    sin.sin_family = AF_INET;
    /* Any local address (all the interfaces) */
    sin.sin_addr.s_addr = htonl(INADDR_ANY);
    /* Set port number, using htons function to use proper byte order */
    sin.sin_port = htons(PORT);

    /*
     * Create the socket. The three arguments are: 1) Internet domain 2) Stream
     * socket 3) Default protocol (TCP in this case)
     */
    listener = socket(AF_INET, SOCK_STREAM, 0);
    if (listener == -1) {
        perror("socket");
        exit(EXIT_FAILURE);
    }

    /* Allow restarting the server despite connections in TIME_WAIT */
    if (setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) == -1) {
        perror("setsockopt");
        exit(EXIT_FAILURE);
    }

    /* Bind the address struct to the socket */
    if (bind(listener, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
        perror("bind");
        exit(EXIT_FAILURE);
    }

    /* Listen on the socket, with 10 max connection requests queued */
    if (listen(listener, 10) < 0) {
        perror("listen");
        exit(EXIT_FAILURE);
    }

    /* Set up SIGCHLD handler to prevent zombie processes */
    memset(&sa, 0, sizeof(sa));
    sa.sa_handler = &sigchld_handler;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = SA_RESTART;
    if (sigaction(SIGCHLD, &sa, NULL) == -1) {
        perror("sigaction");
        exit(EXIT_FAILURE);
    }
    signal(SIGPIPE, SIG_IGN);  /* client left: send() fails with EPIPE */

    while (1) {
        struct sockaddr_storage ss;
        socklen_t slen;
        int fd;

        slen = sizeof(ss);
        /* Accept call creates a new socket for the incoming connection */
        fd = accept(listener, (struct sockaddr *) &ss, &slen);
        if (fd < 0) {
            if (errno == EINTR) {
                continue;
            }
            perror("accept");
        } else {
            pid_t pid = fork();
            if (pid == -1) {
                perror("fork");
            } else if (pid == 0) {
                close(listener);  /* The child does not accept connections */
                handle_child(fd);
                exit(EXIT_SUCCESS);
            }
            close(fd);  /* Parent doesn't need this socket */
        }
    }
}

int main(void) {
    run();

    return EXIT_SUCCESS;
}
src/test_sockets.c

View on GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>     /* exit() */
#include <string.h>     /* memset() */
#include <unistd.h>     /* close() */
#include <signal.h>
#include <sys/types.h>
#include <netinet/in.h> /* Internet structures and functions. */
#include <sys/socket.h> /* Socket functions. */

/**
 * @file test_sockets.c
 *
 * @brief Opens 8 sockets of different domains and types, then waits for
 * Ctrl-C, so that they can be observed with "lsof -p <PID>". The raw
 * sockets (SOCK_RAW) need the root privileges: without them, socket() fails
 * (EPERM on macOS, EPROTONOSUPPORT or EPERM on Linux).
 */

/**
 * New handler of the SIGINT signal: it only interrupts pause() (printf()
 * and exit() are not async-signal-safe, so main() displays the message).
 * @param sig Number of the signal
 */
void handle(int sig) {
    (void) sig;
}

int main(void) {
    int s1; /* socket descriptors for the test */
    int s2;
    int s3;
    int s4;
    int s5;
    int s6;
    int s7;
    int s8;
    struct sigaction action;

    memset(&action, 0, sizeof(action));
    action.sa_handler = &handle;
    sigemptyset(&action.sa_mask);

    /* install the new handler of the SIGINT signal */
    if (sigaction(SIGINT, &action, NULL) == -1) {
        perror("sigaction");
        exit(EXIT_FAILURE);
    }

    /* open sockets in different modes */
    s1 = socket(AF_UNIX, SOCK_STREAM, 0);
    if (s1 == -1) {
        perror("Error opening a stream Unix socket using default protocol");
    } else {
        printf("A stream Unix socket (s1) using default protocol has been opened\n");
    }

    s2 = socket(AF_UNIX, SOCK_DGRAM, 0);
    if (s2 == -1) {
        perror("Error opening a datagram Unix socket using default protocol");
    } else {
        printf("A datagram Unix socket (s2) using default protocol has been opened\n");
    }

    s3 = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (s3 == -1) {
        perror("Error opening a stream socket using TCP");
    } else {
        printf("A stream socket (s3) using TCP has been opened\n");
    }

    s4 = socket(AF_INET, SOCK_STREAM, 0);
    if (s4 == -1) {
        perror("Error opening a stream socket using default protocol");
    } else {
        printf("A stream socket (s4) using default protocol has been opened\n");
    }

    s5 = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if (s5 == -1) {
        perror("Error opening a datagram socket using UDP");
    } else {
        printf("A datagram socket (s5) using UDP has been opened\n");
    }

    s6 = socket(AF_INET, SOCK_DGRAM, 0);
    if (s6 == -1) {
        perror("Error opening a datagram socket using default protocol");
    } else {
        printf("A datagram socket (s6) using default protocol has been opened\n");
    }

    s7 = socket(AF_INET, SOCK_RAW, IPPROTO_IP);
    if (s7 == -1) {
        perror("Error opening a raw socket using IP");
    } else {
        printf("A raw socket (s7) using IP has been opened\n");
    }

    s8 = socket(AF_INET, SOCK_RAW, 0);
    if (s8 == -1) {
        perror("Error opening a raw socket using default protocol");
    } else {
        printf("A raw socket (s8) using default protocol has been opened\n");
    }

    /* wait for Ctrl-C (SIGINT) */
    printf("PID %ld: observe the sockets with \"lsof -p %ld\", then Ctrl-C\n",
           (long) getpid(), (long) getpid());
    pause();
    printf("SIGINT signal received!\n");

    int sockets[] = {s1, s2, s3, s4, s5, s6, s7, s8};
    for (int i = 0; i < 8; i++) {
        if (sockets[i] != -1) { /* only the sockets actually opened */
            close(sockets[i]);
        }
    }

    return EXIT_SUCCESS;
} 
src/testbind1.c

View on GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#define _POSIX_C_SOURCE 200809L

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h> /* htons(), htonl() */

/**
 * @file testbind1.c
 * @brief Demonstrates creating and binding a TCP/IP stream socket.
 *
 * This program creates a TCP/IP stream socket and binds it to a specified
 * port number on the local host. The program is a basic demonstration of
 * socket programming in C.
 */

int main(int argc, char *argv[]) {
    int sd;
    int port = 5001;  /* Default port */
    struct sockaddr_in name;

    if (argc > 1) {  /* Allow port to be set via command line */
        char *end;
        long value = strtol(argv[1], &end, 10);
        if (*end != '\0' || value < 1 || value > 65535) {
            fprintf(stderr, "Port must be an integer between 1 and 65535\n");
            exit(EXIT_FAILURE);
        }
        port = (int) value;
    }

    /* Create the socket */
    sd = socket(AF_INET, SOCK_STREAM, 0);
    if (sd < 0) {
        perror("socket() failed");
        exit(EXIT_FAILURE);
    }

    /* Give a name to the socket */
    memset(&name, 0, sizeof(name));  /* sin_zero (and sin_len on BSD) */
    name.sin_family = AF_INET;
    name.sin_port = htons(port);
    name.sin_addr.s_addr = htonl(INADDR_ANY);

    if (bind(sd, (struct sockaddr *) &name, sizeof(name)) < 0) {
        perror("bind() failed");
        close(sd);
        exit(EXIT_FAILURE);
    }

    /* Here you could call to listen() if needed */

    printf("Socket bound to port %d\n", port);
    close(sd);

    return EXIT_SUCCESS;
}
src/testbind2.c

View on GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netdb.h>

/**
 * @file testbind2.c
 * @brief Demonstrates creating and binding a TCP/IP stream socket to a
 * specific host.
 *
 * The host name (or address) given on the command line is resolved with
 * getaddrinfo() (gethostbyname() was removed from POSIX in 2008). A stream
 * socket is then created and bound, on port 5001, to the first address that
 * works (slide "getaddrinfo() - essayer chaque adresse").
 *
 * \code{.bash}
 *   $ ./testbind2 localhost
 *   Socket bound to localhost, port 5001
 * \endcode
 */

#define PORT "5001"

int main(int argc, char *argv[]) {
    struct addrinfo hints;
    struct addrinfo *res;
    struct addrinfo *p;
    int sd = -1;
    int err;

    if (argc < 2) {
        fprintf(stderr, "Usage: %s hostname\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC;     /* IPv4 or IPv6 */
    hints.ai_socktype = SOCK_STREAM;
    err = getaddrinfo(argv[1], PORT, &hints, &res);
    if (err != 0) {
        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(err));
        exit(EXIT_FAILURE);
    }

    /* Try each address until the socket can be bound */
    for (p = res; p != NULL; p = p->ai_next) {
        sd = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
        if (sd == -1) {
            continue;
        }
        if (bind(sd, p->ai_addr, p->ai_addrlen) == 0) {
            break;                   /* success */
        }
        close(sd);
        sd = -1;
    }
    freeaddrinfo(res);

    if (sd == -1) {
        fprintf(stderr, "Unable to bind a socket to %s\n", argv[1]);
        exit(EXIT_FAILURE);
    }

    /* Here you could call listen() if needed */

    printf("Socket bound to %s, port %s\n", argv[1], PORT);
    close(sd);

    return EXIT_SUCCESS;
}
src/udp_echo_client.c

View on GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>      /* printf(), fprintf(), perror() */
#include <stdlib.h>     /* exit() */
#include <string.h>     /* memset(), strlen() */
#include <unistd.h>     /* close() */
#include <arpa/inet.h>  /* htons(), inet_pton() */
#include <netinet/in.h> /* struct sockaddr_in */
#include <sys/socket.h> /* socket(), sendto(), recvfrom() */

/**
 * @file udp_echo_client.c
 * @brief Running example: UDP echo sender (port 5001).
 *
 * Lecture: chapter os-11 "Sockets" ("Fil rouge - émetteur UDP (1/2)"
 * and "(2/2)").
 *
 * The sender sends its second argument in one datagram to the receiver
 * (udp_echo_server), then waits for the echo and displays it.
 *
 * Key points:
 *   - the sender does not need bind(): an ephemeral port is chosen at the
 *     first sendto();
 *   - if the datagram or the echo is lost, recvfrom() waits forever: a
 *     timeout should be set (SO_RCVTIMEO, or poll()).
 * The port can be changed at compile time: -DPORT=5002.
 *
 * \code{.bash}
 *   $ ./udp_echo_client 127.0.0.1 salut
 *   écho : salut
 * \endcode
 */

#ifndef PORT
#define PORT 5001
#endif

/**
 * @brief Displays the error message (perror), then exits.
 */
void erreur(const char *msg) {
    perror(msg);
    exit(EXIT_FAILURE);
}

int main(int argc, char *argv[]) {
    struct sockaddr_in srv;
    char buf[1500];

    if (argc != 3) {
        fprintf(stderr, "usage : %s ip msg\n", argv[0]);
        exit(EXIT_FAILURE);
    }
    int fd = socket(AF_INET, SOCK_DGRAM, 0);
    if (fd == -1) {
        erreur("socket");
    }
    memset(&srv, 0, sizeof srv);
    srv.sin_family = AF_INET;
    srv.sin_port = htons(PORT);
    if (inet_pton(AF_INET, argv[1], &srv.sin_addr) != 1) {
        fprintf(stderr, "adresse invalide\n");
        exit(EXIT_FAILURE);
    }

    if (sendto(fd, argv[2], strlen(argv[2]), 0,
               (struct sockaddr *) &srv, sizeof srv) == -1) {
        erreur("sendto");
    }
    ssize_t n = recvfrom(fd, buf, sizeof buf - 1, 0, NULL, NULL);
    if (n == -1) {
        erreur("recvfrom");
    }
    buf[n] = '\0';
    printf("écho : %s\n", buf);
    close(fd);

    return EXIT_SUCCESS;
}
src/udp_echo_server.c

View on GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>      /* printf(), perror() */
#include <stdlib.h>     /* exit() */
#include <string.h>     /* memset() */
#include <unistd.h>     /* close() */
#include <arpa/inet.h>  /* htons(), htonl(), inet_ntop() */
#include <netinet/in.h> /* struct sockaddr_in, INADDR_ANY */
#include <sys/socket.h> /* socket(), bind(), recvfrom(), sendto() */

/**
 * @file udp_echo_server.c
 * @brief Running example: UDP echo receiver on port 5001.
 *
 * Lecture: chapter os-11 "Sockets" ("Fil rouge - récepteur UDP (1/2)"
 * and "(2/2)").
 *
 * The receiver binds its socket to port 5001, waits for datagrams with
 * recvfrom() and sends each one back to its sender with sendto().
 *
 * Key points:
 *   - only the type changes: SOCK_DGRAM; no listen(), no accept();
 *   - a single socket for all the clients;
 *   - the echo goes back to the address filled in by recvfrom();
 *   - one reception = one whole datagram (a too small buffer truncates it).
 * The port can be changed at compile time: -DPORT=5002.
 *
 * \code{.bash}
 *   $ ./udp_echo_server                 # terminal 1
 *   5 octets de 127.0.0.1
 *   $ ./udp_echo_client 127.0.0.1 salut # terminal 2
 *   écho : salut
 * \endcode
 */

#ifndef PORT
#define PORT 5001
#endif

/**
 * @brief Displays the error message (perror), then exits.
 */
void erreur(const char *msg) {
    perror(msg);
    exit(EXIT_FAILURE);
}

int main(void) {
    struct sockaddr_in adr, cli;
    char buf[1500];

    int fd = socket(AF_INET, SOCK_DGRAM, 0);
    if (fd == -1) {
        erreur("socket");
    }
    memset(&adr, 0, sizeof adr);
    adr.sin_family = AF_INET;
    adr.sin_port = htons(PORT);
    adr.sin_addr.s_addr = htonl(INADDR_ANY);
    if (bind(fd, (struct sockaddr *) &adr, sizeof adr) == -1) {
        erreur("bind");
    }

    for (;;) {
        socklen_t lg = sizeof cli;
        char ip[INET_ADDRSTRLEN];
        ssize_t n = recvfrom(fd, buf, sizeof buf, 0,
                             (struct sockaddr *) &cli, &lg);
        if (n == -1) {
            erreur("recvfrom");
        }
        inet_ntop(AF_INET, &cli.sin_addr, ip, sizeof ip);
        printf("%zd octets de %s\n", n, ip);
        fflush(stdout);
        if (sendto(fd, buf, n, 0,               /* echo */
                   (struct sockaddr *) &cli, lg) == -1) {
            perror("sendto");
        }
    }
}