1 /* Byte Stream Connection Server Example
2 Copyright (C) 1991-2024 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, see <https://www.gnu.org/licenses/>.
22 #include <sys/types.h>
23 #include <sys/socket.h>
24 #include <netinet/in.h>
31 read_from_client (int filedes
)
36 nbytes
= read (filedes
, buffer
, MAXMSG
);
49 fprintf (stderr
, "Server: got message: `%s'\n", buffer
);
57 extern int make_socket (uint16_t port
);
59 fd_set active_fd_set
, read_fd_set
;
61 struct sockaddr_in clientname
;
64 /* Create the socket and set it up to accept connections. */
65 sock
= make_socket (PORT
);
66 if (listen (sock
, 1) < 0)
72 /* Initialize the set of active sockets. */
73 FD_ZERO (&active_fd_set
);
74 FD_SET (sock
, &active_fd_set
);
78 /* Block until input arrives on one or more active sockets. */
79 read_fd_set
= active_fd_set
;
80 if (select (FD_SETSIZE
, &read_fd_set
, NULL
, NULL
, NULL
) < 0)
86 /* Service all the sockets with input pending. */
87 for (i
= 0; i
< FD_SETSIZE
; ++i
)
88 if (FD_ISSET (i
, &read_fd_set
))
92 /* Connection request on original socket. */
94 size
= sizeof (clientname
);
96 (struct sockaddr
*) &clientname
,
104 "Server: connect from host %s, port %hd.\n",
105 inet_ntoa (clientname
.sin_addr
),
106 ntohs (clientname
.sin_port
));
107 FD_SET (new, &active_fd_set
);
111 /* Data arriving on an already-connected socket. */
112 if (read_from_client (i
) < 0)
115 FD_CLR (i
, &active_fd_set
);