是否可以配置 UDP 多播套接字以便调用 write() 而不是 sendto()?
Can a UDP multicast socket be configured so that write() can be called rather than sendto()?
我正在 Linux Ubuntu.
上编写 C++ 多播应用程序
在我的 C++ 多播发送器中 class 我这样做:
uint16_t port = 5678;
const char* group = "239.128.128.128";
int fd = socket(AF_INET, SOCK_DGRAM, 0);
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(group);
addr.sin_port = htons(port);
const char* buf = "Hi there";
size_t bytes_to_write = 8;
size_t bytes_sent = sendto(fd, buf, bytes_to_write, 0, (struct sockaddr*) &addr, sizeof(addr));
有什么方法可以配置文件描述符,以便我可以调用 write() 而不是 sendto()?我原以为会有一个 setsockopt 选项或类似选项来执行此操作?
是的。
根据文档 man 7 udp
When
connect(2) is called on the socket, the default destination address
is set and datagrams can now be sent using send(2) or write(2)
without specifying a destination address.
并且,为了一般性,connect 的 POSIX 规范说
If the initiating socket is not connection-mode, then connect() shall set the socket's peer address, and no connection is made. For SOCK_DGRAM sockets, the peer address identifies where all datagrams are sent on subsequent send() functions, and limits the remote sender for subsequent recv() functions.
检查这些东西的文档总是值得的, 并非难以理解。 FWIW 我不记得你是否需要 connect()
或 bind()
,我花了几秒钟才知道。
我正在 Linux Ubuntu.
上编写 C++ 多播应用程序在我的 C++ 多播发送器中 class 我这样做:
uint16_t port = 5678;
const char* group = "239.128.128.128";
int fd = socket(AF_INET, SOCK_DGRAM, 0);
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(group);
addr.sin_port = htons(port);
const char* buf = "Hi there";
size_t bytes_to_write = 8;
size_t bytes_sent = sendto(fd, buf, bytes_to_write, 0, (struct sockaddr*) &addr, sizeof(addr));
有什么方法可以配置文件描述符,以便我可以调用 write() 而不是 sendto()?我原以为会有一个 setsockopt 选项或类似选项来执行此操作?
是的。
根据文档 man 7 udp
When connect(2) is called on the socket, the default destination address is set and datagrams can now be sent using send(2) or write(2) without specifying a destination address.
并且,为了一般性,connect 的 POSIX 规范说
If the initiating socket is not connection-mode, then connect() shall set the socket's peer address, and no connection is made. For SOCK_DGRAM sockets, the peer address identifies where all datagrams are sent on subsequent send() functions, and limits the remote sender for subsequent recv() functions.
检查这些东西的文档总是值得的, 并非难以理解。 FWIW 我不记得你是否需要 connect()
或 bind()
,我花了几秒钟才知道。