This is sockets/list_host_addresses.c, an example to accompany the book, The Linux Programming Interface.

This file is not printed in the book; it is a supplementary file for Chapter 61.

The source code file is copyright 2022, Michael Kerrisk, and is licensed under the GNU General Public License, version 3.

In the listing below, the names of Linux system calls and C library functions are hyperlinked to manual pages from the Linux man-pages project, and the names of functions implemented in the book are hyperlinked to the implementations of those functions.


Download sockets/list_host_addresses.c

  Cover of The Linux Programming Interface

Function list (Bold in this list means a function is not static)

/* list_host_addresses.c

   List host's network interfaces and IP addresses.
#define _GNU_SOURCE     /* To get definition of NI_MAXHOST */
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netdb.h>
#include <ifaddrs.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <linux/if_link.h>
main(int argc, char *argv[])
    struct ifaddrs *ifaddr;
    if (getifaddrs(&ifaddr) == -1) {

    /* Walk through linked list, ignoring loopback interface and
       non-AF_INET* addresses */

    for (; ifaddr != NULL; ifaddr = ifaddr->ifa_next) {

        if (ifaddr->ifa_addr == NULL || strcmp(ifaddr->ifa_name, "lo") == 0)

        int family = ifaddr->ifa_addr->sa_family;

        if (family != AF_INET && family != AF_INET6)

        /* Display interface name and address */

        char host[NI_MAXHOST];

        int s = getnameinfo(ifaddr->ifa_addr,
                    (family == AF_INET) ? sizeof(struct sockaddr_in) :
                                          sizeof(struct sockaddr_in6),
                    host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
        if (s != 0) {
            printf("getnameinfo() failed: %s\n", gai_strerror(s));

        printf("%-16s %s\n", ifaddr->ifa_name, host);



Download sockets/list_host_addresses.c

Note that, in most cases, the programs rendered in these web pages are not free standing: you'll typically also need a few other source files (mostly in the lib/ subdirectory) as well. Generally, it's easier to just download the entire source tarball and build the programs with make(1). By hovering your mouse over the various hyperlinked include files and function calls above, you can see which other source files this file depends on.

Valid XHTML 1.1