Blame manual/examples/mkfsock.c

Packit 6c4009
/* Example of Local-Namespace Sockets
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 <stddef.h>
Packit 6c4009
#include <stdio.h>
Packit 6c4009
#include <errno.h>
Packit 6c4009
#include <stdlib.h>
Packit 6c4009
#include <string.h>
Packit 6c4009
#include <sys/socket.h>
Packit 6c4009
#include <sys/un.h>
Packit 6c4009
Packit 6c4009
int
Packit 6c4009
make_named_socket (const char *filename)
Packit 6c4009
{
Packit 6c4009
  struct sockaddr_un name;
Packit 6c4009
  int sock;
Packit 6c4009
  size_t size;
Packit 6c4009
Packit 6c4009
  /* Create the socket.  */
Packit 6c4009
  sock = socket (PF_LOCAL, SOCK_DGRAM, 0);
Packit 6c4009
  if (sock < 0)
Packit 6c4009
    {
Packit 6c4009
      perror ("socket");
Packit 6c4009
      exit (EXIT_FAILURE);
Packit 6c4009
    }
Packit 6c4009
Packit 6c4009
  /* Bind a name to the socket.  */
Packit 6c4009
  name.sun_family = AF_LOCAL;
Packit 6c4009
  strncpy (name.sun_path, filename, sizeof (name.sun_path));
Packit 6c4009
  name.sun_path[sizeof (name.sun_path) - 1] = '\0';
Packit 6c4009
Packit 6c4009
  /* The size of the address is
Packit 6c4009
     the offset of the start of the filename,
Packit 6c4009
     plus its length (not including the terminating null byte).
Packit 6c4009
     Alternatively you can just do:
Packit 6c4009
     size = SUN_LEN (&name);
Packit 6c4009
  */
Packit 6c4009
  size = (offsetof (struct sockaddr_un, sun_path)
Packit 6c4009
	  + strlen (name.sun_path));
Packit 6c4009
Packit 6c4009
  if (bind (sock, (struct sockaddr *) &name, size) < 0)
Packit 6c4009
    {
Packit 6c4009
      perror ("bind");
Packit 6c4009
      exit (EXIT_FAILURE);
Packit 6c4009
    }
Packit 6c4009
Packit 6c4009
  return sock;
Packit 6c4009
}