gpt4 book ai didi

c++ - 在广播套接字中发送私有(private) UDP 消息

转载 作者:行者123 更新时间:2023-12-04 17:19:34 24 4
gpt4 key购买 nike

我有一个广播 channel ,人们用 UDP 和它的工作方式在上面交谈,但是我有时想发送私有(private)消息,但我的套接字处于广播模式?我有我想私下联系的人的 IP。创建一个新的套接字非常烦人,所以我想有一种方法可以使用正确的 Ipaddress 但不是广播发送消息。

struct addrinfo *res = nullptr, *it;
struct addrinfo hints;

memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_DGRAM;

getaddrinfo(ip_address.c_str(), port.c_str(), &hints, &res);

for (it = res; it != NULL; it = it->ai_next) {
socket_ = socket(it->ai_family, it->ai_socktype, it->ai_protocol);

sockaddr_ = it->ai_addr;
socklen_ = it->ai_addrlen;

break;
}


int enable = 1;

setsockopt(socket_, SOL_SOCKET, SO_BROADCAST, &enable, sizeof(int));

然后发送我的广播消息我这样做

sendto(socket_, message, len, 0, sockaddr_, socklen_);

那么我应该更改 sockaddr 吗?请帮助我:)

[编辑] 目前我决定用我想要的人的 Ipadress 创建一个新套接字 + 端口但它非常“沉重”并且根本没有优化(我认为)

最佳答案

sendto 的参数告诉它要发送到哪个地址,而您要发送到广播地址。

If sendto() is used on a connection-mode (SOCK_STREAM, SOCK_SEQPACKET) socket, the arguments dest_addr and addrlen are ignored (and the error EISCONN may be returned when they are not NULL and 0), and the error ENOTCONN is returned when the socket was not actually connected. Otherwise, the address of the target is given by dest_addr with addrlen specifying its size. For sendmsg(), the address of the target is given by msg.msg_name, with msg.msg_namelen specifying its size.

关于c++ - 在广播套接字中发送私有(private) UDP 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67087896/

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