Skip several analyzer socket tests on hppa*-*-hpux*
[official-gcc.git] / gcc / testsuite / gcc.dg / analyzer / fd-glibc-byte-stream-connection-server.c
blobfcbcc740170e67201d7efc867ff08532d7eb8713
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* } } */
6 #include <stdio.h>
7 #include <errno.h>
8 #include <stdlib.h>
9 #include <unistd.h>
10 #include <sys/types.h>
11 #include <sys/socket.h>
12 #include <netinet/in.h>
13 #include <arpa/inet.h>
14 #include <netdb.h>
16 #define PORT 5555
17 #define MAXMSG 512
19 int
20 make_socket (uint16_t port)
22 int sock;
23 struct sockaddr_in name;
25 /* Create the socket. */
26 sock = socket (PF_INET, SOCK_STREAM, 0);
27 if (sock < 0)
29 perror ("socket");
30 exit (EXIT_FAILURE);
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)
39 perror ("bind");
40 exit (EXIT_FAILURE);
43 return sock;
46 int
47 read_from_client (int filedes)
49 char buffer[MAXMSG];
50 int nbytes;
52 nbytes = read (filedes, buffer, MAXMSG);
53 if (nbytes < 0)
55 /* Read error. */
56 perror ("read");
57 exit (EXIT_FAILURE);
59 else if (nbytes == 0)
60 /* End-of-file. */
61 return -1;
62 else
64 /* Data read. */
65 fprintf (stderr, "Server: got message: `%s'\n", buffer);
66 return 0;
70 int
71 main (void)
73 int sock;
74 fd_set active_fd_set, read_fd_set;
75 int i;
76 struct sockaddr_in clientname;
77 socklen_t size;
79 /* Create the socket and set it up to accept connections. */
80 sock = make_socket (PORT);
81 if (listen (sock, 1) < 0)
83 perror ("listen");
84 exit (EXIT_FAILURE);
87 /* Initialize the set of active sockets. */
88 FD_ZERO (&active_fd_set);
89 FD_SET (sock, &active_fd_set);
91 while (1)
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)
97 perror ("select");
98 exit (EXIT_FAILURE);
101 /* Service all the sockets with input pending. */
102 for (i = 0; i < FD_SETSIZE; ++i)
103 if (FD_ISSET (i, &read_fd_set))
105 if (i == sock)
107 /* Connection request on original socket. */
108 int new;
109 size = sizeof (clientname);
110 new = accept (sock,
111 (struct sockaddr *) &clientname,
112 &size);
113 if (new < 0)
115 perror ("accept");
116 exit (EXIT_FAILURE);
118 fprintf (stderr,
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);
124 else
126 /* Data arriving on an already-connected socket. */
127 if (read_from_client (i) < 0)
129 close (i);
130 FD_CLR (i, &active_fd_set);