本地套接字是进程间通信的一种方式,除了本地套接字外还有管道、消息队列等
lib/common.h
#ifndef __COMMON_H__
#define __COMMON_H__
#include <sys/socket.h>
#include <netdb.h>
#include <errno.h>
#include <pthread.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <strings.h>
#include <sys/un.h>
#endif
server.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "lib/common.h"
#define MAXLINE 1024
int main() {
int sockfd = socket(AF_LOCAL, SOCK_STREAM, 0);
struct sockaddr_un server_addr, client_addr;
server_addr.sun_family = AF_LOCAL;
char* path = "/home/grape/test/test.sock";
unlink(path);
strcpy(server_addr.sun_path, path);
if (bind(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
error(1, errno, "bind is error");
}
listen(sockfd, 0);
int client_len = sizeof(client_addr);
int fd;
if ((fd = accept(sockfd, (struct sockaddr*)&client_addr, &client_len)) < 0) {
error(1, errno, "accept is failed");
}
char buf[MAXLINE];
while (1) {
int n = read(fd, buf, MAXLINE);
if (n == 0) {
printf("client exit");
break;
}
buf[n] = 0;
printf("buf: %s\n", buf);
strcpy(buf, "recived");
if (write(fd, buf, strlen(buf)) != strlen(buf)) {
error(1, errno, "write error");
}
}
close(fd);
close(sockfd);
return 0;
}
client.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "lib/common.h"
#define MAXLINE 1024
int main() {
int sockfd = socket(AF_LOCAL, SOCK_STREAM, 0);
if (sockfd < 0) {
error(2, errno, "create socket failed!!");
}
struct sockaddr_un server_addr;
server_addr.sun_family = AF_LOCAL;
strcpy(server_addr.sun_path, "/home/grape/test/test.sock");
if (connect(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
error(1, errno, "connect failed");
}
char buf[MAXLINE];
while (scanf("%s", buf) != EOF) {
if (write(sockfd, buf, strlen(buf)) != strlen(buf)) {
error(1, errno, "write error");
}
int n = read(sockfd, buf, MAXLINE);
if (n == 0) {
error(1, errno, "server terminated prematurely");
}
buf[n] = 0;
printf("ret: %s\n", buf);
}
return 0;
}
本地套接字使用SOCK_DGRAM的时候,使用和IPV4网络套接字相同