服务器端:
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <stddef.h>
char buf[100];
void main(void)
{int sersock,cltsock;
int len,clen;
int ret=0;
struct sockaddr_un seraddr,cltaddr;
sersock=socket(AF_UNIX,SOCK_STREAM,0);
if(sersock<0) {return ;}
memset(&seraddr,0,sizeof(seraddr));
seraddr.sun_family=AF_UNIX;
sprintf(seraddr.sun_path,"ser");
unlink(seraddr.sun_path);
len = offsetof(struct sockaddr_un, sun_path) + strlen(seraddr.sun_path);
if (0 > bind(sersock, (struct sockaddr *)&seraddr, sizeof(struct sockaddr)) || //
0 > listen(sersock, 10))
{printf("fail to bind and lisen \n");}
printf("Start to listen connect request from unix socket name: \"%s\"\n", seraddr.sun_path);
while(1)
{ clen=sizeof(cltaddr);
cltsock=accept(sersock,(struct sockaddr*)&cltaddr,&clen);
if(0>cltsock)
{printf("ACCEPT error\n");}
clen -= offsetof(struct sockaddr_un, sun_path);
cltaddr.sun_path[clen] = 0;
while(1)
{
ret = recv(cltsock,buf,100, 0);
buf[ret]=0;
printf(buf);
if (ret != send(cltsock, buf,ret, 0))
{printf("AgentSrv send message fail\n");}
}
}
close(cltsock);
close(sersock);
}
客户端:
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <stddef.h>
char buf[100];
void main(void)
{
int cltsock, len, err;
struct sockaddr_un cltaddr;
struct sockaddr_un seraddr;
int ret;
cltsock = socket(AF_UNIX, SOCK_STREAM, 0);
if (cltsock < 0)
{
printf("socket creat error !!!\n");
return;
}
memset(&cltaddr, 0, sizeof(cltaddr));
cltaddr.sun_family = AF_UNIX;
sprintf(cltaddr.sun_path, "clt");
len = offsetof(struct sockaddr_un, sun_path) + strlen(cltaddr.sun_path);
unlink(cltaddr.sun_path); //若已存在,先删除之
if (bind(cltsock, (struct sockaddr *)&cltaddr, sizeof(struct sockaddr)) < 0) //绑定之后才能建立文件路劲
{
printf("Bind socket to addr fail\n");
close(cltsock);
return;
}
/* if(chmod(cltaddr.sun_path, S_IRWXU) < 0) //修改文件权限:可以不需要
{
printf("Set %s rwx for user only fail\n", cltaddr.sun_path);
return;
}
*/
//设置服务端地址
memset((char*)&seraddr, 0, sizeof(seraddr));
seraddr.sun_family = AF_UNIX;
strcpy(seraddr.sun_path, "ser");
len = offsetof(struct sockaddr_un, sun_path) + strlen("ser");
//以客户端socket连接服务端地址
if (connect(cltsock, (struct sockaddr *)&seraddr, len) < 0)
{
printf("Connect agent sock \"%s\" fail\n", "ser");
return;
}
while(1)
{printf("input a line:");
gets(buf);
len=strlen(buf);
printf("\nsend cnt:%d\n",len);
if (len != send(cltsock, buf, len, 0))
{
printf("Send msg fail\n");
return ;
}
ret = recv(cltsock,buf,100, 0);
buf[ret]=0;
printf("\nreceived: %s\n",buf);
}
close(cltsock);
}
本文转自 a_liujin 51CTO博客,原文链接:http://blog.51cto.com/a1liujin/1662514,如需转载请自行联系原作者