Blame manual/examples/filesrv.c

Packit 6c4009
/* Datagram Socket Example
Packit 6c4009
   Copyright (C) 1991-2018 Free Software Foundation, Inc.
Packit 6c4009
Packit 6c4009
   This program is free software; you can redistribute it and/or
Packit 6c4009
   modify it under the terms of the GNU General Public License
Packit 6c4009
   as published by the Free Software Foundation; either version 2
Packit 6c4009
   of the License, or (at your option) any later version.
Packit 6c4009
Packit 6c4009
   This program is distributed in the hope that it will be useful,
Packit 6c4009
   but WITHOUT ANY WARRANTY; without even the implied warranty of
Packit 6c4009
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
Packit 6c4009
   GNU General Public License for more details.
Packit 6c4009
Packit 6c4009
   You should have received a copy of the GNU General Public License
Packit 6c4009
   along with this program; if not, if not, see <http://www.gnu.org/licenses/>.
Packit 6c4009
*/
Packit 6c4009
Packit 6c4009
#include <stdio.h>
Packit 6c4009
#include <errno.h>
Packit 6c4009
#include <stdlib.h>
Packit 6c4009
#include <sys/socket.h>
Packit 6c4009
#include <sys/un.h>
Packit 6c4009
Packit 6c4009
#define SERVER	"/tmp/serversocket"
Packit 6c4009
#define MAXMSG	512
Packit 6c4009
Packit 6c4009
int
Packit 6c4009
main (void)
Packit 6c4009
{
Packit 6c4009
  int sock;
Packit 6c4009
  char message[MAXMSG];
Packit 6c4009
  struct sockaddr_un name;
Packit 6c4009
  size_t size;
Packit 6c4009
  int nbytes;
Packit 6c4009
Packit 6c4009
  /* Remove the filename first, it's ok if the call fails */
Packit 6c4009
  unlink (SERVER);
Packit 6c4009
Packit 6c4009
  /* Make the socket, then loop endlessly. */
Packit 6c4009
  sock = make_named_socket (SERVER);
Packit 6c4009
  while (1)
Packit 6c4009
    {
Packit 6c4009
      /* Wait for a datagram. */
Packit 6c4009
      size = sizeof (name);
Packit 6c4009
      nbytes = recvfrom (sock, message, MAXMSG, 0,
Packit 6c4009
			 (struct sockaddr *) & name, &size);
Packit 6c4009
      if (nbytes < 0)
Packit 6c4009
	{
Packit 6c4009
	  perror ("recfrom (server)");
Packit 6c4009
	  exit (EXIT_FAILURE);
Packit 6c4009
	}
Packit 6c4009
Packit 6c4009
      /* Give a diagnostic message. */
Packit 6c4009
      fprintf (stderr, "Server: got message: %s\n", message);
Packit 6c4009
Packit 6c4009
      /* Bounce the message back to the sender. */
Packit 6c4009
      nbytes = sendto (sock, message, nbytes, 0,
Packit 6c4009
		       (struct sockaddr *) & name, size);
Packit 6c4009
      if (nbytes < 0)
Packit 6c4009
	{
Packit 6c4009
	  perror ("sendto (server)");
Packit 6c4009
	  exit (EXIT_FAILURE);
Packit 6c4009
	}
Packit 6c4009
    }
Packit 6c4009
}