Skip to content

Instantly share code, notes, and snippets.

@giwa
Last active May 21, 2016 11:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save giwa/5c84de41efa445f6005b180a382ecb9c to your computer and use it in GitHub Desktop.
Save giwa/5c84de41efa445f6005b180a382ecb9c to your computer and use it in GitHub Desktop.
simple unix domain socket
#include <stdio.h>
#include <sys/socket.h>
#include <sys/un.h>
int main() {
int fd;
struct sockaddr_un addr;
int ret;
char buff[8192];
struct sockaddr_un from;
int ok = 1;
int len;
if ((fd = socket(PF_UNIX, SOCK_DGRAM, 0)) < 0) {
perror("socket");
ok = 0;
}
if (ok) {
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
strcpy(addr.sun_path, "socketFile");
unlink("socketFile");
if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
perror("bind");
ok = 0;
}
}
if (ok) {
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
strcpy(addr.sun_path, SERVER_SOCK_FILE);
if (connect(fd, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
perror("connect");
ok = 0;
}
}
if (ok) {
strcpy (buff, "data to be sent");
if (send(fd, buff, strlen(buff)+1, 0) == -1) {
perror("send");
ok = 0;
}
printf ("sent\n");
}
if (ok) {
if ((len = recv(fd, buff, 8192, 0)) < 0) {
perror("recv");
ok = 0;
}
printf ("receive %d %s\n", len, buff);
}
if (fd >= 0) {
close(fd);
}
unlink (CLIENT_SOCK_FILE);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment