Local A
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
int main(int argc,const char* argv[])
{
int sockfd = socket(AF_LOCAL,SOCK_STREAM,0);
if(0 > sockfd)
{
perror("socket");
return EXIT_FAILURE;
}
struct sockaddr_un addr = {};
addr.sun_family = AF_LOCAL;
strcpy(addr.sun_path,"sock");
socklen_t socksize = sizeof(addr);
if(bind(sockfd,(struct sockaddr*)&addr,socksize))
{
perror("bind");
return EXIT_FAILURE;
}
if(listen(sockfd,5))
{
perror("listen");
return EXIT_FAILURE;
}
printf("等待连接...\n");
int fd = accept(sockfd,(struct sockaddr*)&addr,&socksize);
if(0 > fd)
{
perror("accept");
return EXIT_FAILURE;
}
char buf[4096] = {};
size_t buf_size = sizeof(buf);
for(;;)
{
printf("recv...");fflush(stdout);
size_t size = recv(fd,buf,buf_size,0);
if(0 == strcmp(buf,"quit"))
{
printf("通信结束\n");
break;
}
printf("%s %u\n",buf,size);
printf(">>>");
gets(buf);
send(fd,buf,strlen(buf)+1,0);
if(0 == strcmp(buf,"quit"))
{
printf("通信结束\n");
break;
}
}
close(sockfd);
remove(addr.sun_path);
}
Local B
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
int main(int argc,const char* argv[])
{
int sockfd = socket(AF_LOCAL,SOCK_STREAM,0);
if(0 > sockfd)
{
perror("socket");
return EXIT_FAILURE;
}
struct sockaddr_un addr = {};
addr.sun_family = AF_LOCAL;
strcpy(addr.sun_path,"sock");
if(connect(sockfd,(struct sockaddr*)&addr,sizeof(addr)))
{
perror("connect");
return EXIT_FAILURE;
}
char buf[4096] = {};
for(;;)
{
printf(">>>");
gets(buf);
send(sockfd,buf,strlen(buf)+1,0);
if(0 == strcmp(buf,"quit"))
{
printf("通信结束\n");
break;
}
printf("recv...");fflush(stdout);
recv(sockfd,buf,sizeof(buf),0);
if(0 == strcmp(buf,"quit"))
{
printf("通信结束\n");
break;
}
printf("%s\n",buf);
}
close(sockfd);
}