1 | /* Datagram 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 <sys/socket.h> |
22 | #include <sys/un.h> |
23 | |
24 | #define SERVER "/tmp/serversocket" |
25 | #define MAXMSG 512 |
26 | |
27 | int |
28 | main (void) |
29 | { |
30 | int sock; |
31 | char message[MAXMSG]; |
32 | struct sockaddr_un name; |
33 | size_t size; |
34 | int nbytes; |
35 | |
36 | /* Remove the filename first, it's ok if the call fails */ |
37 | unlink (SERVER); |
38 | |
39 | /* Make the socket, then loop endlessly. */ |
40 | sock = make_named_socket (SERVER); |
41 | while (1) |
42 | { |
43 | /* Wait for a datagram. */ |
44 | size = sizeof (name); |
45 | nbytes = recvfrom (fd: sock, buf: message, MAXMSG, flags: 0, |
46 | addr: (struct sockaddr *) & name, addr_len: &size); |
47 | if (nbytes < 0) |
48 | { |
49 | perror ("recfrom (server)" ); |
50 | exit (EXIT_FAILURE); |
51 | } |
52 | |
53 | /* Give a diagnostic message. */ |
54 | fprintf (stderr, "Server: got message: %s\n" , message); |
55 | |
56 | /* Bounce the message back to the sender. */ |
57 | nbytes = sendto (fd: sock, buf: message, n: nbytes, flags: 0, |
58 | addr: (struct sockaddr *) & name, addr_len: size); |
59 | if (nbytes < 0) |
60 | { |
61 | perror ("sendto (server)" ); |
62 | exit (EXIT_FAILURE); |
63 | } |
64 | } |
65 | } |
66 | |