server:
#include <stdint.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/un.h>
#define SOCKET_NAME "/tmp/9Lq7BNBnBycd6nxy2.socket"
#define BUFFER_SIZE 12
/**
* https://man7.org/linux/man-pages/man7/unix.7.html
*/
int main() {
int down_flag = 0;
int connection_socket = 0;
struct sockaddr_un name;
int ret;
int addrlen = sizeof(name);
char buffer[1024];
connection_socket = socket(AF_UNIX, SOCK_SEQPACKET, 0);
if (connection_socket == -1) {
perror("socket");
exit(EXIT_FAILURE);
}
memset(&name, '0', addrlen);
name.sun_family = AF_UNIX;
strncpy(name.sun_path, SOCKET_NAME, sizeof(name.sun_path) - 1);
ret = bind(connection_socket, (const struct sockaddr*) &name, sizeof(name));
if (ret == -1) {
perror("bind");
exit(EXIT_FAILURE);
}
if (listen(connection_socket, 20) < 0) {
perror("listen");
goto exit;
}
while (1) {
printf("start accept \n");
int clientFd = accept(connection_socket, NULL, NULL);
if (clientFd < 0) {
perror("accept");
exit(EXIT_FAILURE);
}
printf("new connection \n");
while (1) {
int length = read(clientFd, buffer, 1023);
if (length <= 0) {
printf("read error \n");
perror("read error");
break;
}
buffer[length] = '\0';
printf("%s\n", buffer);
if (strcmp(buffer, "close") == 0) {
printf("%s\n", "close");
down_flag = 1;
break;
}
write(clientFd, buffer, length);
}
close(clientFd);
if (down_flag) {
break;
}
sleep(1);
}
exit:
close(connection_socket);
unlink(SOCKET_NAME);
return EXIT_SUCCESS;
}
客户端:
#include <stdint.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/un.h>
#define SOCKET_NAME "/tmp/9Lq7BNBnBycd6nxy2.socket"
#define BUFFER_SIZE 12
/**
* https://man7.org/linux/man-pages/man7/unix.7.html
*/
int main() {
int data_socket = 0;
struct sockaddr_un addr;
int ret;
int addrlen = sizeof(addr);
char buffer2[124];
data_socket = socket(AF_UNIX, SOCK_SEQPACKET, 0);
if (data_socket == -1) {
perror("socket");
return EXIT_FAILURE;
}
memset(&addr, '0', addrlen);
addr.sun_family = AF_UNIX;
strncpy(addr.sun_path, SOCKET_NAME, sizeof(addr.sun_path) - 1);
ret = connect(data_socket, (const struct sockaddr*) &addr, sizeof(addr));
if (ret == -1) {
perror("bind");
return EXIT_FAILURE;
}
char buffer[] = "For portability clear the whole structure";
ret = write(data_socket, buffer, strlen(buffer) + 1);
int length = read(data_socket, buffer2, strlen(buffer2));
buffer2[length] = '\0';
printf("result: %s", buffer2);
strcpy(buffer, "close");
ret = write(data_socket, buffer, strlen(buffer) + 1);
printf("%s\n", "exit now");
close(data_socket);
return EXIT_SUCCESS;
}