sockets/id_echo_sv.c

This is sockets/id_echo_sv.c (Listing 60-2, page 1241), an example from the book, The Linux Programming Interface.

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

This page shows the "distribution" or "book" version of the file (why are there two versions?), or the differences between the two versions. You can switch between the views using the tabs below.

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.

  Cover of The Linux Programming Interface
+/* id_echo_sv.c
+
+   This program implements a daemon that provides the UDP "echo" service. It
+   reads datagrams and then sends copies back to the originating address.
+
+   NOTE: this program must be run under a root login, in order to allow the
+   "echo" port (7) to be bound. Alternatively, for test purposes, you can edit
+   id_echo.h and replace the SERVICE name with a suitable unreserved port
+   number (e.g., "51000"), and make a corresponding change in the client.
+
+   See also id_echo_cl.c.
+*/
 #include <syslog.h>
 #include "id_echo.h"
 #include "become_daemon.h"
 
 int
 main(int argc, char *argv[])
 {
     int sfd;
     ssize_t numRead;
     socklen_t len;
     struct sockaddr_storage claddr;
     char buf[BUF_SIZE];
     char addrStr[IS_ADDR_STR_LEN];
 
     if (becomeDaemon(0) == -1)
         errExit("becomeDaemon");
 
     sfd = inetBind(SERVICE, SOCK_DGRAM, NULL);
     if (sfd == -1) {
         syslog(LOG_ERR, "Could not create server socket (%s)", strerror(errno));
         exit(EXIT_FAILURE);
     }
 
     /* Receive datagrams and return copies to senders */
 
     for (;;) {
         len = sizeof(struct sockaddr_storage);
         numRead = recvfrom(sfd, buf, BUF_SIZE, 0,
                            (struct sockaddr *) &claddr, &len);
         if (numRead == -1)
             errExit("recvfrom");
 
         if (sendto(sfd, buf, numRead, 0, (struct sockaddr *) &claddr, len)
                         != numRead)
             syslog(LOG_WARNING, "Error echoing response to %s (%s)",
                     inetAddressStr((struct sockaddr *) &claddr, len,
                                    addrStr, IS_ADDR_STR_LEN),
                     strerror(errno));
     }
 }

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