summaryrefslogtreecommitdiff
path: root/src/af_unix.c
blob: 41037ee4b7ad792f3f3ab6b0919a756999fa1cea (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// SPDX-License-Identifier: GPL-2.0+
/* Create an AF_UNIX socket.
 * Copyright (C) 2017 Red Hat, Inc. All Rights Reserved.
 * Written by David Howells (dhowells@redhat.com)
 */

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

#define offsetof(TYPE, MEMBER)	((size_t)&((TYPE *)0)->MEMBER)

int main(int argc, char *argv[])
{
	struct sockaddr_un sun;
	struct stat st;
	size_t len, max;
	int fd;

	if (argc != 2) {
		fprintf(stderr, "Format: %s <socketpath>\n", argv[0]);
		exit(2);
	}

	max = sizeof(sun.sun_path);
	len = strlen(argv[1]);
	if (len >= max) {
		fprintf(stderr, "Filename too long (max %zu)\n", max);
		exit(2);
	}

	fd = socket(AF_UNIX, SOCK_DGRAM, 0);
	if (fd < 0) {
		perror("socket");
		exit(1);
	}

	memset(&sun, 0, sizeof(sun));
	sun.sun_family = AF_UNIX;
	strcpy(sun.sun_path, argv[1]);
	if (bind(fd, (struct sockaddr *)&sun, sizeof(sun)) == -1) {
		perror("bind");
		exit(1);
	}

	if (stat(argv[1], &st)) {
		fprintf(stderr, "Couldn't stat socket after creation: %m\n");
		exit(1);
	}

	exit(0);
}