Sending private UDP message in broadcast socket

Viewed 91

I have a broadcast channel with people talking on it in UDP and its working however i want to send sometimes private message , but my socket is in broadcast mode ? I have the Ip on the people i want to contact privately. It's very annoying to create a new socket , so i suppose there is a way to juste send the message with the good Ipaddress but not in broadcast.

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));

Then to send my broadcast msg i do this

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

So should I change sockaddr ? Pls help me :)

[Edit] For the moment i decided to create a new socket with Ipadress of the guy i want talk + port but it's very "heavy" and not optimised at all (I think)

1 Answers

sendto's parameters tells it which address to send to and you are sending to a broadcast address .

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.

Related