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

#define UNIX_DOMAIN_SOCKET_PATH "/tmp/unix-domain-socket"

int main(void)
{
	int sock;
	struct sockaddr_un sa = {0};
	int fd;
	char buf[128] = {0};
	int read_size;

	// サーバーソケット作成
	sock = socket(AF_UNIX, SOCK_STREAM, 0);
	if (sock == -1) {
		perror("socket");
		return 1;
	}

	// struct sockaddr_un 作成
	sa.sun_family = AF_UNIX;
	strcpy(sa.sun_path, UNIX_DOMAIN_SOCKET_PATH);

	// bind
	if (bind(sock, (struct sockaddr*) &sa, sizeof(struct sockaddr_un)) == -1) {
		perror("bind");
		goto CLOSE_SOCKET;
	}

	// listen
	if (listen(sock, 128) == -1) {
		perror("listen");
		goto CLOSE_SOCKET;
	}

	while (1) {
		// accept (受信待ち)
		if ((fd = accept(sock, NULL, NULL)) == -1) {
			perror("accept");
			goto CLOSE_SOCKET;
		}

		// read (データ受信)
		if ((read_size = read(fd, buf, sizeof(buf)-1)) == -1) {
			perror("read");
			close(fd);
			goto CLOSE_SOCKET;
		}
		else {
			// 受信データの表示
			buf[read_size] = '\0';
			printf("message: %s\n", buf);
		}

		// close (クローズ)
		if (close(fd) == -1) {
			perror("close");
			goto CLOSE_SOCKET;
		}

		// 終端文字列の確認
		if (strcmp(buf, "eof") == 0) {
			break;
		}
	}

CLOSE_SOCKET:
	close(sock);

	return 1;
}
