Skip to content

Instantly share code, notes, and snippets.

@dhilst
Last active June 24, 2016 18:51
Show Gist options
  • Save dhilst/7958fd777e50b227901a to your computer and use it in GitHub Desktop.
Save dhilst/7958fd777e50b227901a to your computer and use it in GitHub Desktop.
unix socket
/* nice unix socket exaple from: http://beej.us/guide/bgipc/output/html/multipage/unixsock.html */#include "libus.h"
#include <errno.h>
#define SOCK_PATH "unixsocket"
#define die(msg) ({perror(msg);exit(EXIT_FAILURE);})
int main(int argc, char **argv)
{
char *slash = strchr(argv[0], '/');
argv[0] = (slash ? slash + 1 : argv[0]);
if (!strncmp(argv[0], "usserver", strlen("usserver"))) {
argv[0] = (slash ? slash + 1 : argv[0]);
int sock;
struct sockaddr_un local, remote;
int len;
int error;
sock = socket(AF_UNIX, SOCK_STREAM, 0);
local.sun_family = AF_UNIX;
strncpy(local.sun_path, SOCK_PATH, strlen(SOCK_PATH));
unlink(local.sun_path);
len = strlen(local.sun_path) + sizeof(local.sun_family);
error = bind(sock, (struct sockaddr *)&local, len);
if (error) die("bind");
error = listen(sock, 5);
if (error) die ("listem");
for(;;) {
char str[100];
int s2;
int done, n;
unsigned int t = sizeof(remote);
printf("Waiting for a connection...\n");
s2 = accept(sock, (struct sockaddr *)&remote, &t);
if (s2 == -1)
die("accept");
printf("Connected.\n");
done = 0;
do {
n = recv(s2, str, 100, 0);
if (n <= 0) {
if (n < 0) perror("recv");
done = 1;
}
if (!done)
if (send(s2, str, n, 0) < 0) {
perror("send");
done = 1;
}
} while (!done);
close(s2);
}
} else if (!strncmp(argv[0], "usclient", strlen("usclient"))) {
int s, len;
struct sockaddr_un remote;
char str[100];
s = socket(AF_UNIX, SOCK_STREAM, 0);
if (s == -1) die("socket");
puts("Trying to connect.");
remote.sun_family = AF_UNIX;
strncpy(remote.sun_path, SOCK_PATH, strlen(SOCK_PATH));
len = strlen(SOCK_PATH) + sizeof(remote.sun_family);
int error = connect(s, (struct sockaddr *)&remote, len);
if (error) die("connect");
puts("Connected.");
while (printf("> "), fgets(str, 100, stdin), !feof(stdin)) {
int n = send(s, str, strlen(str), 0);
if (n == -1) die("send");
int t = recv(s, str, 100, 0);
if (t > 0)
printf("echo > %s", str);
else
die("Server closed the connection.");
}
}
return 0;
}
libus: libus.c libus.h
$(CC) $(CFLAGS) $(LDFLAGS) -o $@ $<
clean:
rm libus
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment