+/**
+ * Perform AF-independent multicast sender setup.
+ *
+ * \param fd The connected socket descriptor.
+ * \param ttl UDPv4 multicast TTL or UDPv6 multicast number of hops.
+ * Use -1 to mean default, 0..255 otherwise.
+ * \param iface The outgoing multicast interface, or NULL for the default.
+ *
+ * \return Zero if okay, negative on error.
+ */
+static int mcast_sender_setup(struct udp_target *ut, int ttl, char *iface)
+{
+ struct sockaddr_storage ss;
+ socklen_t sslen = sizeof(ss);
+
+ const int on = 1;
+ int id = iface == NULL ? 0 : if_nametoindex(iface);
+
+ if (getpeername(ut->fd, (struct sockaddr *)&ss, &sslen) < 0)
+ goto err;
+
+ if (iface != NULL && id == 0)
+ PARA_WARNING_LOG("could not resolve interface %s, using default", iface);
+
+ /* RFC 3493, 5.2: -1 means 'use kernel default' */
+ if (ttl < 0 || ttl > 255)
+ ttl = -1;
+
+ switch (ss.ss_family) {
+ case AF_INET:
+ if (!IN_MULTICAST(htonl(((struct sockaddr_in *)&ss)->sin_addr.s_addr)))
+ return 0;
+ if (id != 0) {
+#ifdef HAVE_IP_MREQN
+ struct ip_mreqn mn;
+
+ memset(&mn, 0, sizeof(mn));
+ mn.imr_ifindex = id;
+ if (setsockopt(ut->fd, IPPROTO_IP, IP_MULTICAST_IF, &mn, sizeof(mn)) < 0)
+ goto err;
+#else
+ PARA_ERROR_LOG("No support for setting outgoing IPv4 mcast interface.");
+#endif
+ }
+ /*
+ * Enable receiving multicast messages generated on the local host
+ * At least on Linux, this is enabled by default.
+ */
+ if (setsockopt(ut->fd, IPPROTO_IP, IP_MULTICAST_LOOP, &on, sizeof(on)) < 0)
+ break;
+
+ /* Default: use local subnet (do not flood out into the WAN) */
+ if (ttl == -1)
+ ttl = 1;
+ if (setsockopt(ut->fd, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl)) < 0)
+ break;
+ return 0;
+ case AF_INET6:
+ if (!IN6_IS_ADDR_MULTICAST(&((struct sockaddr_in6 *)&ss)->sin6_addr))
+ return 0;
+ if (id != 0 &&
+ setsockopt(ut->fd, IPPROTO_IPV6, IPV6_MULTICAST_IF, &id, sizeof(id)) < 0)
+ break;
+ if (setsockopt(ut->fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &on, sizeof(on)) < 0)
+ break;
+ if (setsockopt(ut->fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &ttl, sizeof(ttl)) < 0)
+ break;
+ return 0;
+ default:
+ PARA_ERROR_LOG("address family %d not supported", ss.ss_family);
+ return -E_ADDRESS_LOOKUP;
+ }
+err:
+ return -ERRNO_TO_PARA_ERROR(errno);
+}
+