#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include <sys/un.h>
#define ERR_MSG(msg) do{\
fprintf(stderr, "__%d__:", __LINE__);\
perror(msg);\
}while(0)
int main(int argc, const char *argv[])
{
//创建域套接字:报式套接字
int sfd = socket(AF_UNIX, SOCK_DGRAM, 0);
if(sfd < 0)
{
ERR_MSG("socket");
return -1;
}
//判断套接字文件是否存在
//如果存在则删除套接字文件
if(access("./unix", F_OK) == 0)
{
if(unlink("./unix") < 0)
{
ERR_MSG("unlink");
return -1;
}
}
//填充服务器的地址信息结构体-->需要绑定到套接字上
struct sockaddr_un sun;
sun.sun_family = AF_UNIX;
strcpy(sun.sun_path, "./unix");
//将地址信息结构体绑定到套接字上
if(bind(sfd, (struct sockaddr*)&sun, sizeof(sun)) < 0)
{
ERR_MSG("bind");
return -1;
}
printf("bind success\n");
char buf[128] = "";
struct sockaddr_un cun;
socklen_t addrlen = sizeof(cun);
while(1)
{
bzero(buf, sizeof(buf));
//接收数据
if(recvfrom(sfd, buf, sizeof(buf), 0, (struct sockaddr*)&cun, &addrlen) < 0)
{
ERR_MSG("recvfrom");
return -1;
}
printf("path:%s|%s\n", cun.sun_path, buf);
//发送数据--->谁发送给我 我就发还给谁
strcat(buf, "*-*");
if(sendto(sfd, buf, sizeof(buf), 0, (struct sockaddr*)&cun, sizeof(cun)) < 0)
{
ERR_MSG("sendto");
return -1;
}
printf("sendto success\n");
}
//关闭文件描述符
close(sfd);
return 0;
}
版权声明:本文为weixin_43386810原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。