#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>

#define BUFSIZE	4096

int main(int argc, char *argv[])
{
  struct sockaddr_un name;
  char buf[BUFSIZE], *path = "/tmp/serv_sock";
  int r;

  if (argc > 1) path = argv[1];

  /* Create socket, initially un-connected. */
  int sock = socket(AF_UNIX, SOCK_DGRAM, 0);
  if (sock < 0) {
    perror("socket");
    exit(1);
  }
  
  /* Create name (filesystem socket file) */
  name.sun_family = AF_UNIX;
  strcpy(name.sun_path, path);

  /* Remove stale socket file if present */
  unlink(path);

  /* Bind socket to name: */
  if (bind(sock, (struct sockaddr *)&name, sizeof(struct sockaddr_un))) {
    perror("bind");
    exit(1);
  }
  printf("Listening at %s\n", path);

  while((r = read(sock, buf, BUFSIZE)) > 0) {
    printf("%.*s", r, buf);
  }
  return 0;
}
