#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_STREAM, 0);
if(sfd < 0)
{
ERR_MSG("socket");
return -1;
}
//判断套接字文件是否存在 access
if(access("./unix", F_OK) == 0)
{
//如果存在则删除该文件 unlink
if(unlink("./unix") < 0)
{
ERR_MSG("unlink");
return -1;
}
}
//填充地址信息结构体
struct sockaddr_un sun;
sun.sun_family = AF_UNIX; //必须填AF_UNIX
strcpy(sun.sun_path, "./unix"); //套接字文件路径
//将IP和端口绑定到套接字上
if(bind(sfd, (struct sockaddr*)&sun, sizeof(sun)) < 0)
{
ERR_MSG("bind");
return -1;
}
printf("bind success\n");
-
struct sockaddr_un cun;
socklen_t addrlen = sizeof(cun);
//取出新的文件描述符
int newfd = accept(sfd, (struct sockaddr*)&cun, &addrlen);
if(newfd < 0)
{
ERR_MSG("accept");
return -1;
}
printf("newfd=%d 连接成功\n", newfd);
char buf[128] = "";
ssize_t res = 0;
while(1)
{
bzero(buf, sizeof(buf));
//newfd中读取数据
res = recv(newfd, buf, sizeof(buf), 0);
if(res < 0)
{
ERR_MSG("recv");
return -1;
}
else if(0 == res)
{
fprintf(stderr, "newfd = %d 客户端关闭\n", newfd);
break;
}
printf("newfd=%d : %s\n", newfd, buf);
strcat(buf, "*-*");
//发送数据到客户端
if(send(newfd, buf, sizeof(buf), 0) < 0)
{
ERR_MSG("send");
return -1;
}
printf("发送到newfd = %d客户端成功\n", newfd);
}
close(newfd);
//关闭文件描述符
close(sfd);
return 0;
}
网络编程-TCP本地通讯
于 2022-08-15 20:28:14 首次发布