sockets/i6d_ucase_sv.cThis is sockets/i6d_ucase_sv.c (Listing 59-3, page 1208), 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. |
+/* i6d_ucase_sv.c + + A server that receives datagrams, converts their contents to uppercase, and + then returns them to the senders. + + See also i6d_ucase_cl.c. +*/ #include "i6d_ucase.h" int main(int argc, char *argv[]) { struct sockaddr_in6 svaddr, claddr; int sfd, j; ssize_t numBytes; socklen_t len; char buf[BUF_SIZE]; char claddrStr[INET6_ADDRSTRLEN]; + /* Create a datagram socket bound to an address in the IPv6 domain */ + sfd = socket(AF_INET6, SOCK_DGRAM, 0); if (sfd == -1) errExit("socket"); memset(&svaddr, 0, sizeof(struct sockaddr_in6)); svaddr.sin6_family = AF_INET6; svaddr.sin6_addr = in6addr_any; /* Wildcard address */ svaddr.sin6_port = htons(PORT_NUM); if (bind(sfd, (struct sockaddr *) &svaddr, sizeof(struct sockaddr_in6)) == -1) errExit("bind"); /* Receive messages, convert to uppercase, and return to client */ for (;;) { len = sizeof(struct sockaddr_in6); numBytes = recvfrom(sfd, buf, BUF_SIZE, 0, (struct sockaddr *) &claddr, &len); if (numBytes == -1) errExit("recvfrom"); + /* Display address of client that sent the message */ + if (inet_ntop(AF_INET6, &claddr.sin6_addr, claddrStr, INET6_ADDRSTRLEN) == NULL) printf("Couldn't convert client address to string\n"); else printf("Server received %ld bytes from (%s, %u)\n", (long) numBytes, claddrStr, ntohs(claddr.sin6_port)); for (j = 0; j < numBytes; j++) buf[j] = toupper((unsigned char) buf[j]); if (sendto(sfd, buf, numBytes, 0, (struct sockaddr *) &claddr, len) != numBytes) fatal("sendto"); } }
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.