From e8bf81794f412b27261be0f2aa4eb287352041af Mon Sep 17 00:00:00 2001
From: Guus Sliepen <guus@tinc-vpn.org>
Date: Tue, 13 Nov 2012 15:05:41 +0100
Subject: [PATCH] Send broadcast packets using a random socket, and properly
 support IPv6.

Before it would always use the first socket, and always send an IPv4 broadcast packet. That
works fine in a lot of situations, but it is better to try all sockets, and to send IPv6 packets
on IPv6 sockets. This is especially important for users that are on IPv6-only networks or that
have multiple physical network interfaces, although in the latter case it probably requires
them to use the ListenAddress variable to create a separate socket for each interface.
---
 src/net_packet.c | 18 ++++++++++++++----
 1 file changed, 14 insertions(+), 4 deletions(-)

diff --git a/src/net_packet.c b/src/net_packet.c
index 5290fd6b..2abe16eb 100644
--- a/src/net_packet.c
+++ b/src/net_packet.c
@@ -541,11 +541,21 @@ static void send_udppacket(node_t *n, vpn_packet_t *origpkt) {
 	/* Overloaded use of priority field: -1 means local broadcast */
 
 	if(origpriority == -1 && n->prevedge) {
-		broadcast.in.sin_family = AF_INET;
-		broadcast.in.sin_addr.s_addr = -1;
-		broadcast.in.sin_port = n->prevedge->address.in.sin_port;
+		sock = rand() % listen_sockets;
+		memset(&broadcast, 0, sizeof broadcast);
+		if(listen_socket[sock].sa.sa.sa_family == AF_INET6) {
+			broadcast.in6.sin6_family = AF_INET6;
+			broadcast.in6.sin6_addr.s6_addr[0x0] = 0xff;
+			broadcast.in6.sin6_addr.s6_addr[0x1] = 0x02;
+			broadcast.in6.sin6_addr.s6_addr[0xf] = 0x01;
+			broadcast.in6.sin6_port = n->prevedge->address.in.sin_port;
+			broadcast.in6.sin6_scope_id = listen_socket[sock].sa.in6.sin6_scope_id;
+		} else {
+			broadcast.in.sin_family = AF_INET;
+			broadcast.in.sin_addr.s_addr = -1;
+			broadcast.in.sin_port = n->prevedge->address.in.sin_port;
+		}
 		sa = &broadcast;
-		sock = 0;
 	} else {
 		if(origpriority == -1)
 			origpriority = 0;
-- 
2.39.5