filesrv.c 1.7 KB

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