如何使用SOCK_DGRAM制作双向unix域套接字? [英] How to make two-directional unix domain sockets with SOCK_DGRAM?
问题描述
我正在尝试编写一个简单的Unix数据报服务器/客户端,并且遇到了一些问题.我想要的是一个在数据报套接字上侦听并将对收到的每条消息的回复发送给原始发件人的服务器.我决定先尝试使用socat
作为服务器",然后用C编写客户端.我正在像这样运行socat:
I am trying to write a simple Unix datagram server/client, and am having some problems. What I want is a server that listens on a datagram socket and sends a reply to every message received, to the original sender. I decided to try first using socat
to be the "server" and writing the client in C. I am running socat like this:
socat UNIX-DGRAM:/tmp/test.socket,fork EXEC:echo
据我所知,应该听/tmp/test.socket
并回复使用相同字符串接收到的所有内容?然后,我有一个客户端程序,看起来像这样(为清楚起见,删除了错误检查):
To the best of my understanding this should listen on /tmp/test.socket
and reply to everything that is received with the same string? Then I have a client program that looks like this (error checking removed for clarity):
int s = socket(AF_UNIX, SOCK_DGRAM, 0);
struct sockaddr_un sa;
sa.sun_family = AF_UNIX;
strcpy(sa.sun_path, "/tmp/test.socket");
const char *data = "Testing data";
int err = sendto(s, data, strlen(data), 0, (struct sockaddr *)(&sa), sizeof(struct sockaddr_un));
printf("Sent!\n");
unsigned char *buffer = malloc(BUFFER_LENGTH);
struct sockaddr_storage recv_sa;
int recv_sa_len = 0;
int recv_len = recvfrom(s, buffer, BUFFER_LENGTH, 0, (struct sockaddr *)&recv_sa, &recv_sa_len);
for (int i = 0; i < recv_len; i++) {
putc(buffer[i], stdout);
}
printf("\n");
它应该发送数据包(有效),接收数据包,然后将其打印出来,但是程序似乎无法接收该数据包.我在这里做错什么,还是对Unix套接字有基本的误解?谢谢!
It should send the packet (that works), receive a packet, and then print it out, but the program doesn't seem to be capable of receiving the packet. What am I doing wrong here, or do I have a fundamental misunderstanding about Unix sockets? Thanks!
推荐答案
看看客户机/服务器程序的Michael Kerrisk的AF_UNIX SOCK_DGRAM示例(服务器)发表在他的《 Linux编程接口》第57章中.
Take a look at the Michael Kerrisk's AF_UNIX SOCK_DGRAM example of the client/server program (client, server) published in his book The Linux Programming Interface, chapter 57.
这篇关于如何使用SOCK_DGRAM制作双向unix域套接字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!