unix-socket

unix socket C example
git clone https://git.parazyd.org/unix-socket
Log | Files | Refs

server.c (989B)


      1 #include <sys/types.h>
      2 #include <sys/socket.h>
      3 #include <sys/un.h>
      4 #include <stdio.h>
      5 #include <stdlib.h>
      6 #include <unistd.h>
      7 
      8 #define NAME "socket"
      9 
     10 int main(void)
     11 {
     12 	int sock, msgsock, rval;
     13 	struct sockaddr_un server;
     14 	char buf[1024];
     15 
     16 	sock = socket(AF_UNIX, SOCK_STREAM, 0);
     17 	if (sock < 0) {
     18 		perror("opening stream socket");
     19 		exit(1);
     20 	}
     21 
     22 	server.sun_family = AF_UNIX;
     23 	strcpy(server.sun_path, NAME);
     24 	if (bind(sock, (struct sockaddr *)&server, sizeof(struct sockaddr_un))) {
     25 		perror("binding stream socket");
     26 		exit(1);
     27 	}
     28 
     29 	printf("Socket has name %s\n", server.sun_path);
     30 	listen(sock, 5);
     31 
     32 	for (;;) {
     33 		msgsock = accept(sock, 0, 0);
     34 		if (msgsock == -1) {
     35 			perror("accept");
     36 		} else do {
     37 			memset(buf, 0, sizeof(buf));
     38 			if ((rval = read(msgsock, buf, 1024)) < 0)
     39 				perror("reading stream message");
     40 			else if (rval == 0)
     41 				printf("Ending connection\n");
     42 			else
     43 				printf("-->%s\n", buf);
     44 		} while (rval > 0);
     45 		close(msgsock);
     46 	}
     47 
     48 	close(sock);
     49 	unlink(NAME);
     50 }