创建步骤:
1 创建socket:
lfd=unix_socket = socket(AF_UNIX, SOCK_STREAM, 0);//选择tcp协议
2 绑定:
(此结构体通过 man 7 unix 查看)
struct sockaddr_un serv;
bzero(&serv,sizeof(serv));
serv.sun_family=AF_UNIX;
strcpy(serv.sun_path,"./serv.sock");//创建sock文件的路径,该文件最好不存在,否则报错
bind(lfd,(struct sockaddr*)&serv,sizeof(serv));
3 监听:
listen;
4 接收新的客户端连接
cfd=accept();
5 while(1)
{
read();
write();
}
6 close(lfd);
close(cfd);
服务端:
cpp
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include <sys/un.h>
#include <sys/socket.h>
#include<ctype.h>
int main()
{
int lfd=socket(AF_UNIX,SOCK_STREAM,0);
if(lfd<0)
{
perror("socket error");
return 0;
}
unlink("serv.sock");//存在则删除此文件
struct sockaddr_un serv;
bzero(&serv,sizeof(serv));
serv.sun_family=AF_UNIX;
strcpy(serv. sun_path,"./serv.sock");
bind(lfd,(struct sockaddr*)&serv,sizeof(serv));
listen(lfd,128);
struct sockaddr_un client;
socklen_t len;
len=sizeof(client);
int cfd=accept(lfd,(struct sockaddr*)&client,&len);
if(cfd<0)
{
perror("accept error/n");
return -1;
}
printf("client:[%s]\n",client.sun_path);//打印客户端绑定的socket文件名
char buf[128];
int i;
while(1)
{
memset(buf,0x00,sizeof(buf));
int n=read(cfd,buf,sizeof(buf));
if(n<=0)
{
printf("read error or client close\n");
return -1;
}
printf("n==[%d],buf==[%s]\n",n,buf);
write(cfd,buf,n);
}
close(cfd);
close(lfd);
return 0;
}
我们可以使用nc -U serv.sock连接
客户端:
cpp
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include <sys/un.h>
#include <sys/socket.h>
#include<ctype.h>
int main()
{
int cfd=socket(AF_UNIX,SOCK_STREAM,0);
if(cfd<0)
{
perror("socket error");
return 0;
}
unlink("client.sock");
struct sockaddr_un client;
bzero(&client,sizeof(client));
client.sun_family=AF_UNIX;
strcpy(client. sun_path,"./client.sock");
bind(cfd,(struct sockaddr*)&client,sizeof(client));//绑定,不然服务端打印不出来
struct sockaddr_un serve;
serve.sun_family=AF_UNIX;
strcpy(serve. sun_path,"./serv.sock");
connect(cfd,(struct sockaddr*)&serve,sizeof(serve));
char buf[128];
int i;
while(1)
{
memset(buf,0x00,sizeof(buf));
int n=read(STDIN_FILENO,buf,sizeof(buf));
write(cfd,buf,n);
memset(buf,0x00,sizeof(buf));
read(cfd,buf,sizeof(buf));
printf("n==[%d],buf==[%s]\n",n,buf);
}
close(cfd);
return 0;
}