Unix sockets demo
This commit is contained in:
parent
e07b9a5eff
commit
1a505c032e
5 changed files with 234 additions and 0 deletions
73
socket/socket.c
Normal file
73
socket/socket.c
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/un.h>
|
||||
|
||||
#define SOCKET_PATH "/tmp/demosocket"
|
||||
#define BUF_SIZE 128
|
||||
|
||||
int main(void) {
|
||||
int server_fd, client_fd;
|
||||
struct sockaddr_un addr;
|
||||
char buf[BUF_SIZE];
|
||||
|
||||
// Clean up any leftover socket file
|
||||
unlink(SOCKET_PATH);
|
||||
|
||||
// Create socket
|
||||
server_fd = socket(AF_UNIX, SOCK_STREAM, 0);
|
||||
if (server_fd == -1) {
|
||||
perror("socket");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
// Zero out and set up the address structure
|
||||
memset(&addr, 0, sizeof(addr));
|
||||
addr.sun_family = AF_UNIX;
|
||||
strncpy(addr.sun_path, SOCKET_PATH, sizeof(addr.sun_path) - 1);
|
||||
|
||||
// Bind the socket to the path
|
||||
if (bind(server_fd, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
|
||||
perror("bind");
|
||||
close(server_fd);
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
// Listen for a connection
|
||||
if (listen(server_fd, 1) == -1) {
|
||||
perror("listen");
|
||||
close(server_fd);
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
printf("Server listening on %s...\n", SOCKET_PATH);
|
||||
|
||||
// Accept a connection
|
||||
client_fd = accept(server_fd, NULL, NULL);
|
||||
if (client_fd == -1) {
|
||||
perror("accept");
|
||||
close(server_fd);
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
// Receive a message
|
||||
ssize_t received = recv(client_fd, buf, BUF_SIZE - 1, 0);
|
||||
if (received > 0) {
|
||||
buf[received] = '\0';
|
||||
printf("Received: %s", buf);
|
||||
|
||||
// Send a reply
|
||||
const char *reply = "Got your message!\n";
|
||||
send(client_fd, reply, strlen(reply), 0);
|
||||
} else {
|
||||
perror("recv");
|
||||
}
|
||||
|
||||
// Clean up
|
||||
close(client_fd);
|
||||
close(server_fd);
|
||||
unlink(SOCKET_PATH);
|
||||
return 0;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue