Update copyright dates with scripts/update-copyrights
[glibc.git] / manual / examples / inetcli.c
blobc95bc1fcc7ea5ea2b6c3366c8a326966388f0a7a
1 /* Byte Stream Socket Example
2 Copyright (C) 1991-2023 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/>.
18 #include <stdio.h>
19 #include <errno.h>
20 #include <stdlib.h>
21 #include <unistd.h>
22 #include <sys/types.h>
23 #include <sys/socket.h>
24 #include <netinet/in.h>
25 #include <netdb.h>
27 #define PORT 5555
28 #define MESSAGE "Yow!!! Are we having fun yet?!?"
29 #define SERVERHOST "www.gnu.org"
31 void
32 write_to_server (int filedes)
34 int nbytes;
36 nbytes = write (filedes, MESSAGE, strlen (MESSAGE) + 1);
37 if (nbytes < 0)
39 perror ("write");
40 exit (EXIT_FAILURE);
45 int
46 main (void)
48 extern void init_sockaddr (struct sockaddr_in *name,
49 const char *hostname,
50 uint16_t port);
51 int sock;
52 struct sockaddr_in servername;
54 /* Create the socket. */
55 sock = socket (PF_INET, SOCK_STREAM, 0);
56 if (sock < 0)
58 perror ("socket (client)");
59 exit (EXIT_FAILURE);
62 /* Connect to the server. */
63 init_sockaddr (&servername, SERVERHOST, PORT);
64 if (0 > connect (sock,
65 (struct sockaddr *) &servername,
66 sizeof (servername)))
68 perror ("connect (client)");
69 exit (EXIT_FAILURE);
72 /* Send data to the server. */
73 write_to_server (sock);
74 close (sock);
75 exit (EXIT_SUCCESS);