72 lines
1.7 KiB
C
72 lines
1.7 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <sys/socket.h>
|
|
#include <sys/un.h>
|
|
#include <unistd.h>
|
|
|
|
/* Unix sockets need a path */
|
|
#define SOCK_PATH "/tmp/demosocket"
|
|
#define BUF_SIZE 128
|
|
|
|
char buf[BUF_SIZE];
|
|
|
|
int main(void) {
|
|
struct sockaddr_un addr;
|
|
int server_fd, client_fd;
|
|
|
|
// Unlink this in case its still around
|
|
unlink(SOCK_PATH);
|
|
|
|
server_fd = socket(AF_UNIX, SOCK_STREAM, 0);
|
|
if (server_fd == -1) {
|
|
perror("Error: Could not open socket...\n");
|
|
exit(EXIT_FAILURE);
|
|
}
|
|
|
|
// Wipe this for security
|
|
memset(&addr, 0, sizeof(struct sockaddr_un));
|
|
addr.sun_family = AF_UNIX;
|
|
snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", SOCK_PATH);
|
|
|
|
if (bind(server_fd, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
|
|
perror("Could not bind server...\n");
|
|
close(server_fd);
|
|
exit(EXIT_FAILURE);
|
|
}
|
|
|
|
if (listen(server_fd, 1) == -1) {
|
|
perror("Listen");
|
|
close(server_fd);
|
|
exit(EXIT_FAILURE);
|
|
}
|
|
|
|
printf("Server listening on %s...\n", SOCK_PATH);
|
|
|
|
while (1) {
|
|
// This will block until a message is recieved
|
|
client_fd = accept(server_fd, NULL, NULL);
|
|
if (client_fd == -1) {
|
|
perror("accept");
|
|
close(server_fd);
|
|
exit(EXIT_FAILURE);
|
|
}
|
|
|
|
ssize_t received = recv(client_fd, buf, BUF_SIZE - 1, 0);
|
|
if (received > 0) {
|
|
buf[received] = '\0';
|
|
printf("Server got: %s\n", buf);
|
|
|
|
// Send a reply
|
|
const char *reply = "pong!\n";
|
|
send(client_fd, reply, strlen(reply), 0);
|
|
} else {
|
|
perror("recv");
|
|
}
|
|
}
|
|
|
|
close(client_fd);
|
|
close(server_fd);
|
|
unlink(SOCK_PATH);
|
|
return 0;
|
|
}
|