I am writing a small program that sends and receive multicast packets.I need to set the outgoing interface with its name (e.g. eth0) rather than its address. Therefore I have to use struct ip_mreqn (rather than struct in_addr) so that I could use its imr_ifindex field to set the interface index (which I can get using interface's name).
However for some reason it doesn't work. The call to setsockopt() works fine but the following call to sendto() returns "Invalid argument" error. Of course the error disappears if I replace ip_mreqn with in_addr and use interface's address instead.
Following is my code:
sd = socket(AF_INET, SOCK_DGRAM, 0);
struct ip_mreqn addr;
addr.imr_ifindex = if_nametoindex("eth0");
setsockopt(sd, IPPROTO_IP, IP_MULTICAST_IF, &addr, sizeof(addr);
struct sockaddr_in sock_addr;
memset((char *) &sock_addr, 0, sizeof(sock_addr));
sock_addr.sin_family = AF_INET;
sock_addr.sin_port = destination_port;
sock_addr.sin_addr.s_addr = destination_address;
char msg[] = "abc";
while (sendto(sd, msg, sizeof(msg), 0, reinterpret_cast<const sockaddr*>(&sock_addr),
sizeof(sock_addr)) < 0)
throw std::runtime_error(strerror(errno));
Is there any problem in using struct ip_mreqn when setting IP_MULTICAST_IF? Has anyone got any idea? Really appreciate help. Thanks.
Note that destination port and address are already in network byte order.