server.c
#include <stdio.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
// ============================
#include <unistd.h>
// ============================ use close,read,write in this header file
#include <sys/un.h>
int main() {
struct sockaddr_un serveraddr ; // define in <sys/un.h>
serveraddr.sun_family = AF_UNIX ;
char *server_path = "/tmp/unix_socket_test02" ;
strcpy(serveraddr.sun_path , server_path) ;
int sockfd = socket(AF_UNIX , SOCK_STREAM , 0) ;
bind(sockfd , (struct sockaddr*)&serveraddr , sizeof(serveraddr)) ;
listen(sockfd , 10) ;
char readbuf[1000] ;
while(1){
int newsockfd = accept(sockfd,NULL,NULL) ;
int read_len = read(newsockfd,readbuf,1000) ;
readbuf[read_len] = 0 ;
printf("recv : %s\n",readbuf) ;
char writebuf[] = "hello" ;
write(newsockfd, writebuf, sizeof(writebuf)) ;
close(newsockfd) ;
}
return 0;
}
client.c
#include <stdio.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
// ============================
#include <unistd.h>
// ============================ use close,read,write in this header file
#include <sys/un.h>
int main() {
struct sockaddr_un serveraddr ; // define in <sys/un.h>
serveraddr.sun_family = AF_UNIX ;
char *server_path = "/tmp/unix_socket_test02" ;
strcpy(serveraddr.sun_path , server_path) ;
int sockfd = socket(AF_UNIX , SOCK_STREAM , 0) ;
connect(sockfd , (struct sockaddr*)&serveraddr, sizeof(serveraddr)) ;
char readbuf[1000] ;
char writebuf[] = "hello server" ;
write(sockfd,writebuf,sizeof(writebuf)) ;
int read_len = read(sockfd, readbuf, 1000) ;
readbuf[read_len] = 0 ;
printf("recv : %s\n", readbuf) ;
return 0;
}