unix-socket

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

client.c (749B)


      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 DATA "data from client"
      9 
     10 int main(int argc, char *argv[])
     11 {
     12 	int sock;
     13 	struct sockaddr_un server;
     14 	char buf[1024];
     15 
     16 	if (argc < 2) {
     17 		printf("usage: %s <pathname>\n", argv[0]);
     18 		exit(1);
     19 	}
     20 
     21 	sock = socket(AF_UNIX, SOCK_STREAM, 0);
     22 	if (sock < 0) {
     23 		perror("opening stream socket");
     24 		exit(1);
     25 	}
     26 
     27 	server.sun_family = AF_UNIX;
     28 	strcpy(server.sun_path, argv[1]);
     29 
     30 	if (connect(sock, (struct sockaddr *)&server, sizeof(struct sockaddr_un)) < 0) {
     31 		close(sock);
     32 		perror("connecting stream socket");
     33 		exit(1);
     34 	}
     35 
     36 	if (write(sock, DATA, sizeof(DATA)) < 0)
     37 		perror("writing on stream socket");
     38 	close(sock);
     39 }