xf.li | bdd93d5 | 2023-05-12 07:10:14 -0700 | [diff] [blame] | 1 | /* Byte Stream Socket Example |
| 2 | Copyright (C) 1991-2016 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, if not, see <http://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, 0); |
| 56 | if (sock < 0) |
| 57 | { |
| 58 | perror ("socket (client)"); |
| 59 | exit (EXIT_FAILURE); |
| 60 | } |
| 61 | |
| 62 | /* Connect to the server. */ |
| 63 | init_sockaddr (&servername, SERVERHOST, PORT); |
| 64 | if (0 > connect (sock, |
| 65 | (struct sockaddr *) &servername, |
| 66 | sizeof (servername))) |
| 67 | { |
| 68 | perror ("connect (client)"); |
| 69 | exit (EXIT_FAILURE); |
| 70 | } |
| 71 | |
| 72 | /* Send data to the server. */ |
| 73 | write_to_server (sock); |
| 74 | close (sock); |
| 75 | exit (EXIT_SUCCESS); |
| 76 | } |