commit 0dcaf0fcbc48723839e9d6fd5cf06a0b57d284d7
Author: parazyd <parazyd@dyne.org>
Date: Mon, 4 Jan 2021 23:35:56 +0100
Add example.
Diffstat:
A | Makefile | | | 6 | ++++++ |
A | client.c | | | 39 | +++++++++++++++++++++++++++++++++++++++ |
A | server.c | | | 51 | +++++++++++++++++++++++++++++++++++++++++++++++++++ |
3 files changed, 96 insertions(+), 0 deletions(-)
diff --git a/Makefile b/Makefile
@@ -0,0 +1,6 @@
+all: clean
+ cc -o client client.c
+ cc -o server server.c
+
+clean:
+ rm -f client server
diff --git a/client.c b/client.c
@@ -0,0 +1,39 @@
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+#define DATA "data from client"
+
+int main(int argc, char *argv[])
+{
+ int sock;
+ struct sockaddr_un server;
+ char buf[1024];
+
+ if (argc < 2) {
+ printf("usage: %s <pathname>\n", argv[0]);
+ exit(1);
+ }
+
+ sock = socket(AF_UNIX, SOCK_STREAM, 0);
+ if (sock < 0) {
+ perror("opening stream socket");
+ exit(1);
+ }
+
+ server.sun_family = AF_UNIX;
+ strcpy(server.sun_path, argv[1]);
+
+ if (connect(sock, (struct sockaddr *)&server, sizeof(struct sockaddr_un)) < 0) {
+ close(sock);
+ perror("connecting stream socket");
+ exit(1);
+ }
+
+ if (write(sock, DATA, sizeof(DATA)) < 0)
+ perror("writing on stream socket");
+ close(sock);
+}
diff --git a/server.c b/server.c
@@ -0,0 +1,50 @@
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+#define NAME "socket"
+
+int main(void)
+{
+ int sock, msgsock, rval;
+ struct sockaddr_un server;
+ char buf[1024];
+
+ sock = socket(AF_UNIX, SOCK_STREAM, 0);
+ if (sock < 0) {
+ perror("opening stream socket");
+ exit(1);
+ }
+
+ server.sun_family = AF_UNIX;
+ strcpy(server.sun_path, NAME);
+ if (bind(sock, (struct sockaddr *)&server, sizeof(struct sockaddr_un))) {
+ perror("binding stream socket");
+ exit(1);
+ }
+
+ printf("Socket has name %s\n", server.sun_path);
+ listen(sock, 5);
+
+ for (;;) {
+ msgsock = accept(sock, 0, 0);
+ if (msgsock == -1) {
+ perror("accept");
+ } else do {
+ memset(buf, 0, sizeof(buf));
+ if ((rval = read(msgsock, buf, 1024)) < 0)
+ perror("reading stream message");
+ else if (rval == 0)
+ printf("Ending connection\n");
+ else
+ printf("-->%s\n", buf);
+ } while (rval > 0);
+ close(msgsock);
+ }
+
+ close(sock);
+ unlink(NAME);
+}+
\ No newline at end of file