filesrv.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /* Datagram Socket Example
  2. Copyright (C) 1991-2026 Free Software Foundation, Inc.
  3. This program is free software; you can redistribute it and/or
  4. modify it under the terms of the GNU General Public License
  5. as published by the Free Software Foundation; either version 2
  6. of the License, or (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program; if not, see <https://www.gnu.org/licenses/>.
  13. */
  14. #include <stdio.h>
  15. #include <errno.h>
  16. #include <stdlib.h>
  17. #include <sys/socket.h>
  18. #include <sys/un.h>
  19. #include <unistd.h>
  20. #define SERVER "/tmp/serversocket"
  21. #define MAXMSG 512
  22. int
  23. main (void)
  24. {
  25. int sock;
  26. char message[MAXMSG];
  27. struct sockaddr_un name;
  28. socklen_t size;
  29. int nbytes;
  30. /* Remove the filename first, it's ok if the call fails */
  31. unlink (SERVER);
  32. /* Make the socket, then loop endlessly. */
  33. sock = make_named_socket (SERVER);
  34. while (1)
  35. {
  36. /* Wait for a datagram. */
  37. size = sizeof (name);
  38. nbytes = recvfrom (sock, message, MAXMSG, 0,
  39. (struct sockaddr *) & name, &size);
  40. if (nbytes < 0)
  41. {
  42. perror ("recfrom (server)");
  43. exit (EXIT_FAILURE);
  44. }
  45. /* Give a diagnostic message. */
  46. fprintf (stderr, "Server: got message: %s\n", message);
  47. /* Bounce the message back to the sender. */
  48. nbytes = sendto (sock, message, nbytes, 0,
  49. (struct sockaddr *) & name, size);
  50. if (nbytes < 0)
  51. {
  52. perror ("sendto (server)");
  53. exit (EXIT_FAILURE);
  54. }
  55. }
  56. }