1 | /* Byte Stream Socket Example |
2 | Copyright (C) 1991-2022 Free Software Foundation, Inc. |
3 | |
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. |
8 | |
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. |
13 | |
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/>. |
16 | */ |
17 | |
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> |
26 | |
27 | #define PORT 5555 |
28 | #define MESSAGE "Yow!!! Are we having fun yet?!?" |
29 | #define SERVERHOST "www.gnu.org" |
30 | |
31 | void |
32 | write_to_server (int filedes) |
33 | { |
34 | int nbytes; |
35 | |
36 | nbytes = write (filedes, MESSAGE, strlen (MESSAGE) + 1); |
37 | if (nbytes < 0) |
38 | { |
39 | perror ("write" ); |
40 | exit (EXIT_FAILURE); |
41 | } |
42 | } |
43 | |
44 | |
45 | int |
46 | main (void) |
47 | { |
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; |
53 | |
54 | /* Create the socket. */ |
55 | sock = socket (PF_INET, SOCK_STREAM, protocol: 0); |
56 | if (sock < 0) |
57 | { |
58 | perror ("socket (client)" ); |
59 | exit (EXIT_FAILURE); |
60 | } |
61 | |
62 | /* Connect to the server. */ |
63 | init_sockaddr (name: &servername, SERVERHOST, PORT); |
64 | if (0 > connect (fd: sock, |
65 | addr: (struct sockaddr *) &servername, |
66 | len: sizeof (servername))) |
67 | { |
68 | perror ("connect (client)" ); |
69 | exit (EXIT_FAILURE); |
70 | } |
71 | |
72 | /* Send data to the server. */ |
73 | write_to_server (filedes: sock); |
74 | close (fd: sock); |
75 | exit (EXIT_SUCCESS); |
76 | } |
77 | |