From 5f7facdc638104a6d2469d052717c36d70847320 Mon Sep 17 00:00:00 2001 From: Richard Cochran Date: Sun, 20 Nov 2011 18:31:33 +0100 Subject: [PATCH] Bind transmitted packets to the port's network interface. Even though the MCAST_JOIN_GROUP socket option includes the interface index, this applies to the received packets only. To bind the outgoing packets to a particular interface, the IP_MULTICAST_IF option is needed. Signed-off-by: Richard Cochran --- udp.c | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/udp.c b/udp.c index b058a7f..6ce3636 100644 --- a/udp.c +++ b/udp.c @@ -113,6 +113,20 @@ static int interface_index(int fd, char *name) return ifreq.ifr_ifindex; } +static int mcast_bind(int fd, int index) +{ + int err; + struct ip_mreqn req; + memset(&req, 0, sizeof(req)); + req.imr_ifindex = index; + err = setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF, &req, sizeof(req)); + if (err) { + perror("setsockopt IP_MULTICAST_IF"); + return -1; + } + return 0; +} + static int mcast_join(int fd, int index, const struct sockaddr *grp, socklen_t grplen) { @@ -169,6 +183,9 @@ static int open_socket(char *name, struct in_addr *mc_addr, short port) perror("mcast_join"); goto no_option; } + if (mcast_bind(fd, index)) { + goto no_option; + } return fd; no_option: close(fd);