Blame manual/examples/filecli.c

Packit 6c4009
/* Example of Reading Datagrams
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 <unistd.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 CLIENT	"/tmp/mysocket"
Packit 6c4009
#define MAXMSG	512
Packit 6c4009
#define MESSAGE	"Yow!!! Are we having fun yet?!?"
Packit 6c4009
Packit 6c4009
int
Packit 6c4009
main (void)
Packit 6c4009
{
Packit 6c4009
  extern int make_named_socket (const char *name);
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
  /* Make the socket. */
Packit 6c4009
  sock = make_named_socket (CLIENT);
Packit 6c4009
Packit 6c4009
  /* Initialize the server socket address. */
Packit 6c4009
  name.sun_family = AF_LOCAL;
Packit 6c4009
  strcpy (name.sun_path, SERVER);
Packit 6c4009
  size = strlen (name.sun_path) + sizeof (name.sun_family);
Packit 6c4009
Packit 6c4009
  /* Send the datagram. */
Packit 6c4009
  nbytes = sendto (sock, MESSAGE, strlen (MESSAGE) + 1, 0,
Packit 6c4009
		   (struct sockaddr *) & name, size);
Packit 6c4009
  if (nbytes < 0)
Packit 6c4009
    {
Packit 6c4009
      perror ("sendto (client)");
Packit 6c4009
      exit (EXIT_FAILURE);
Packit 6c4009
    }
Packit 6c4009
Packit 6c4009
  /* Wait for a reply. */
Packit 6c4009
  nbytes = recvfrom (sock, message, MAXMSG, 0, NULL, 0);
Packit 6c4009
  if (nbytes < 0)
Packit 6c4009
    {
Packit 6c4009
      perror ("recfrom (client)");
Packit 6c4009
      exit (EXIT_FAILURE);
Packit 6c4009
    }
Packit 6c4009
Packit 6c4009
  /* Print a diagnostic message. */
Packit 6c4009
  fprintf (stderr, "Client: got message: %s\n", message);
Packit 6c4009
Packit 6c4009
  /* Clean up. */
Packit 6c4009
  remove (CLIENT);
Packit 6c4009
  close (sock);
Packit 6c4009
}