有两个简单的程序来演示unix域 DGRAM 套接字。
/* server */
int main(int ac, char *av[])
{
char buf[10];
int mpLogFD, len;
struct sockaddr_un serverAddress;
if((mpLogFD = socket(AF_LOCAL, SOCK_DGRAM, 0)) < 0)
mpExit("sock");
unlink(MPLOGD_SOCK);
memset(&serverAddress, 0, sizeof(serverAddress));
serverAddress.sun_family = AF_LOCAL;
strcpy(serverAddress.sun_path, "/var/run/lsvr.sock");
if(bind(mpLogFD, (struct sockaddr *)&serverAddress, sizeof(serverAddress)) < 0)
mpExit("bind");
perror("svr");
for(;;){
if(recvfrom(mpLogFD, buf, sizeof(buf), 0, (struct sockaddr *)&serverAddress, &len) < 0)
mpExit("recv");
printf("%s\n", buf);
}
}
/* client */
int main(int ac, char *av[])
{
int CliFD, len;
char buf[10];
struct sockaddr_un cliaddr;
if((CliFD = socket(AF_LOCAL, SOCK_DGRAM, 0)) == -1)
mpExit("cli sock");
memset(&cliaddr, 0, sizeof(cliaddr));
cliaddr.sun_family = AF_LOCAL;
strcpy(cliaddr.sun_path, "/var/run/lcli.sock");
if(bind(CliFD, (struct sockaddr *)&cliaddr, sizeof(cliaddr)))
mpExit("cli bind");
len = sizeof(cliaddr);
sprintf(buf, "12345678\n");
if(sendto(CliFD, buf, sizeof(buf), 0, (struct sockaddr *)&cliaddr, len) < 0)
mpExit("cli send");
perror("cli");
}
以下是结果:
[root@jyl opt]# ./logsvr &
2033
svr: Success
[root@jyl opt]# ./logcli
cli: Success
[root@jyl opt]#
这里似乎没有错。但是,我从服务器上得不到任何东西 我不知道为什么它不能像我期望的那样运行。
答案 0 :(得分:1)
您应该发送到/var/run/lsvr.sock
而不是/var/run/lcli.sock
。
此外,您不必在客户端绑定,因此请从客户端发表评论:
/* if(bind(CliFD, (struct sockaddr *)&cliaddr, sizeof(cliaddr)))
mpExit("cli bind");*/