lh | 9ed821d | 2023-04-07 01:36:19 -0700 | [diff] [blame] | 1 | /* Example of Reading Datagrams |
| 2 | Copyright (C) 1991-2015 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 <unistd.h> |
| 21 | #include <stdlib.h> |
| 22 | #include <sys/socket.h> |
| 23 | #include <sys/un.h> |
| 24 | |
| 25 | #define SERVER "/tmp/serversocket" |
| 26 | #define CLIENT "/tmp/mysocket" |
| 27 | #define MAXMSG 512 |
| 28 | #define MESSAGE "Yow!!! Are we having fun yet?!?" |
| 29 | |
| 30 | int |
| 31 | main (void) |
| 32 | { |
| 33 | extern int make_named_socket (const char *name); |
| 34 | int sock; |
| 35 | char message[MAXMSG]; |
| 36 | struct sockaddr_un name; |
| 37 | size_t size; |
| 38 | int nbytes; |
| 39 | |
| 40 | /* Make the socket. */ |
| 41 | sock = make_named_socket (CLIENT); |
| 42 | |
| 43 | /* Initialize the server socket address. */ |
| 44 | name.sun_family = AF_LOCAL; |
| 45 | strcpy (name.sun_path, SERVER); |
| 46 | size = strlen (name.sun_path) + sizeof (name.sun_family); |
| 47 | |
| 48 | /* Send the datagram. */ |
| 49 | nbytes = sendto (sock, MESSAGE, strlen (MESSAGE) + 1, 0, |
| 50 | (struct sockaddr *) & name, size); |
| 51 | if (nbytes < 0) |
| 52 | { |
| 53 | perror ("sendto (client)"); |
| 54 | exit (EXIT_FAILURE); |
| 55 | } |
| 56 | |
| 57 | /* Wait for a reply. */ |
| 58 | nbytes = recvfrom (sock, message, MAXMSG, 0, NULL, 0); |
| 59 | if (nbytes < 0) |
| 60 | { |
| 61 | perror ("recfrom (client)"); |
| 62 | exit (EXIT_FAILURE); |
| 63 | } |
| 64 | |
| 65 | /* Print a diagnostic message. */ |
| 66 | fprintf (stderr, "Client: got message: %s\n", message); |
| 67 | |
| 68 | /* Clean up. */ |
| 69 | remove (CLIENT); |
| 70 | close (sock); |
| 71 | } |