Debian Codegraph @

listings/chapter-5/socket-server.c

raw
1 /***********************************************************************
2 * Code listing from "Advanced Linux Programming," by CodeSourcery LLC *
3 * Copyright (C) 2001 by New Riders Publishing *
4 * See COPYRIGHT for license information. *
5 ***********************************************************************/
6
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <string.h>
10 #include <sys/socket.h>
11 #include <sys/un.h>
12 #include <unistd.h>
13
14 /* Read text from the socket and print it out. Continue until the
15 socket closes. Return non-zero if the client sent a "quit"
16 message, zero otherwise. */
17
18 int server (int client_socket)
19 {
20 while (1) {
21 int length;
22 char* text;
23
24 /* First, read the length of the text message from the socket. If
25 read returns zero, the client closed the connection. */
26 if (read (client_socket, &length, sizeof (length)) == 0)
27 return 0;
28 /* Allocate a buffer to hold the text. */
29 text = (char*) malloc (length);
30 /* Read the text itself, and print it. */
31 read (client_socket, text, length);
32 printf ("%s\n", text);
33 /* Free the buffer. */
34 free (text);
35 /* If the client sent the message "quit", we're all done. */
36 if (!strcmp (text, "quit"))
37 return 1;
38 }
39 }
40
41 int main (int argc, char* const argv[])
42 {
43 const char* const socket_name = argv[1];
44 int socket_fd;
45 struct sockaddr_un name;
46 int client_sent_quit_message;
47
48 /* Create the socket. */
49 socket_fd = socket (PF_LOCAL, SOCK_STREAM, 0);
50 /* Indicate this is a server. */
51 name.sun_family = AF_LOCAL;
52 strcpy (name.sun_path, socket_name);
53 bind (socket_fd, &name, SUN_LEN (&name));
54 /* Listen for connections. */
55 listen (socket_fd, 5);
56
57 /* Repeatedly accept connections, spinning off one server() to deal
58 with each client. Continue until a client sends a "quit" message. */
59 do {
60 struct sockaddr_un client_name;
61 socklen_t client_name_len;
62 int client_socket_fd;
63
64 /* Accept a connection. */
65 client_socket_fd = accept (socket_fd, &client_name, &client_name_len);
66 /* Handle the connection. */
67 client_sent_quit_message = server (client_socket_fd);
68 /* Close our end of the connection. */
69 close (client_socket_fd);
70 }
71 while (!client_sent_quit_message);
72
73 /* Remove the socket file. */
74 close (socket_fd);
75 unlink (socket_name);
76
77 return 0;
78 }