1 /* Example from glibc manual (16.9.7). */
2 /* { dg-require-effective-target sockets } */
3 /* { dg-additional-options "-Wno-analyzer-too-complex" } */
4 /* { dg-skip-if "" { hppa*-*-hpux* powerpc*-*-aix* } } */
10 #include <sys/types.h>
11 #include <sys/socket.h>
12 #include <netinet/in.h>
13 #include <arpa/inet.h>
20 make_socket (uint16_t port
)
23 struct sockaddr_in name
;
25 /* Create the socket. */
26 sock
= socket (PF_INET
, SOCK_STREAM
, 0);
33 /* Give the socket a name. */
34 name
.sin_family
= AF_INET
;
35 name
.sin_port
= htons (port
);
36 name
.sin_addr
.s_addr
= htonl (INADDR_ANY
);
37 if (bind (sock
, (struct sockaddr
*) &name
, sizeof (name
)) < 0)
47 read_from_client (int filedes
)
52 nbytes
= read (filedes
, buffer
, MAXMSG
);
65 fprintf (stderr
, "Server: got message: `%s'\n", buffer
);
74 fd_set active_fd_set
, read_fd_set
;
76 struct sockaddr_in clientname
;
79 /* Create the socket and set it up to accept connections. */
80 sock
= make_socket (PORT
);
81 if (listen (sock
, 1) < 0)
87 /* Initialize the set of active sockets. */
88 FD_ZERO (&active_fd_set
);
89 FD_SET (sock
, &active_fd_set
);
93 /* Block until input arrives on one or more active sockets. */
94 read_fd_set
= active_fd_set
;
95 if (select (FD_SETSIZE
, &read_fd_set
, NULL
, NULL
, NULL
) < 0)
101 /* Service all the sockets with input pending. */
102 for (i
= 0; i
< FD_SETSIZE
; ++i
)
103 if (FD_ISSET (i
, &read_fd_set
))
107 /* Connection request on original socket. */
109 size
= sizeof (clientname
);
111 (struct sockaddr
*) &clientname
,
119 "Server: connect from host %s, port %hd.\n",
120 inet_ntoa (clientname
.sin_addr
),
121 ntohs (clientname
.sin_port
));
122 FD_SET (new, &active_fd_set
);
126 /* Data arriving on an already-connected socket. */
127 if (read_from_client (i
) < 0)
130 FD_CLR (i
, &active_fd_set
);