在广播套接字中发送私有 UDP 消息
Sending private UDP message in broadcast socket
我有一个广播频道,人们用 UDP 和它的工作方式在上面交谈,但是我有时想发送私人消息,但我的套接字处于广播模式?我有我想私下联系的人的 IP。创建一个新的套接字非常烦人,所以我想有一种方法可以用正确的 IP 地址发送消息,但不能在广播中发送。
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.
我有一个广播频道,人们用 UDP 和它的工作方式在上面交谈,但是我有时想发送私人消息,但我的套接字处于广播模式?我有我想私下联系的人的 IP。创建一个新的套接字非常烦人,所以我想有一种方法可以用正确的 IP 地址发送消息,但不能在广播中发送。
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.