1. 头文件
#include <sys/un.h>
2. 数据结构
struct sockaddr_un {
sa_family_t sun_family;
// __SOCKADDR_COMMON (sun_);
// #define __SOCKADDR_COMMON(sa_prefix) \
// sa_family_t sa_prefix##family
// 替换原理,带参数的宏,实参替换形参(整个宏中所有的)
char sun_path[108]; // 字符串(unix域套接字文件的名)
};
3. 服务端流程
1. 创建套接字sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
2. 绑定地址到socket
struct sockaddr_un server_addr;
server_addr.sun_family = AF_UNIX;
strcpy(server_addr.sun_path, "mypath");
ret = bind(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr));
3. 设置为监听模式
ret = listen(sockfd, 10);
4. 接收请求
clientfd = accept(sockfd, NULL, NULL);
5. 接收数据
ret = recv(clientfd, buf, sizeof(buf), 0);
6. 发送数据
ret = send(clientfd, buf, len, 0);
7. 关闭套接字
close(clientfd);
close(sockfd);
4. 客户端流程
1. 创建套接字
sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
2. 连接服务器
struct sockaddr_un server_addr;
server_addr.sun_family = AF_UNIX;
strcpy(server_addr.sun_path, "mypath");
ret = connect(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr));
3. 发送数据
ret = send(clientfd, buf, len, 0);
4. 接收数据
ret = recv(clientfd, buf, sizeof(buf), 0);5. 关闭套接字
close(sockfd);