gpt4 book ai didi

c++ - 是否可以配置 UDP 多播套接字以便调用 write() 而不是 sendto()?

转载 作者:太空狗 更新时间:2023-10-29 12:09:02 27 4
gpt4 key购买 nike

我正在 Linux Ubuntu 上编写 C++ 多播应用程序。

在我的 C++ 多播发送器类中,我这样做:

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(),我花了几秒钟才知道。

关于c++ - 是否可以配置 UDP 多播套接字以便调用 write() 而不是 sendto()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55100042/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com