分类: LINUX
2016-01-11 15:17:31
服务端:
int main()
{
//创建socket
int sockfd=socket(PF_LOCAL, SOCK_DGRAM, 0);
if(sockfd==-1)
perror("创建socket失败"),exit(-1);
//准备通信地址
struct sockaddr_un addr;
addr.sun_family = PF_UNIX;
strcpy(addr.sun_path,"a.sock");
//绑定
int res = bind(sockfd,
(struct sockaddr*)&addr, sizeof(addr));
if(res==-1)perror("绑定失败"),exit(-1);
printf("绑定成功\n");
//通信(用读写文件方式)
char buf[100] = {};
read(sockfd, buf, sizeof(buf));
printf("收到信息:%s\n", buf);
//关闭socket
close(sockfd);
}
客户端:
int main()
{
int sockfd=socket(PF_LOCAL, SOCK_DGRAM, 0);
if(sockfd==-1)
perror("创建socket失败"),exit(-1);
struct sockaddr_un addr;
addr.sun_family = PF_UNIX;
strcpy(addr.sun_path,"a.sock");
//连接
int res = connect(sockfd,
(struct sockaddr*)&addr, sizeof(addr));
if(res==-1)perror("失败"),exit(-1);
printf("成功\n");
write(sockfd, "Hello, Socket!", 14);
close(sockfd);
}