+static void choose_udp_address(const node_t *n, const sockaddr_t **sa, int *sock) {
+ /* Latest guess */
+ *sa = &n->address;
+ *sock = n->sock;
+
+ /* If the UDP address is confirmed, use it. */
+ if(n->status.udp_confirmed)
+ return;
+
+ /* Send every third packet to n->address; that could be set
+ to the node's reflexive UDP address discovered during key
+ exchange. */
+
+ static int x = 0;
+ if(++x >= 3) {
+ x = 0;
+ return;
+ }
+
+ /* Otherwise, address are found in edges to this node.
+ So we pick a random edge and a random socket. */
+
+ int i = 0;
+ int j = rand() % n->edge_tree->count;
+ edge_t *candidate = NULL;
+
+ for splay_each(edge_t, e, n->edge_tree) {
+ if(i++ == j) {
+ candidate = e->reverse;
+ break;
+ }
+ }
+
+ if(candidate) {
+ *sa = &candidate->address;
+ *sock = rand() % listen_sockets;
+ }
+
+ /* Make sure we have a suitable socket for the chosen address */
+ if(listen_socket[*sock].sa.sa.sa_family != (*sa)->sa.sa_family) {
+ for(int i = 0; i < listen_sockets; i++) {
+ if(listen_socket[i].sa.sa.sa_family == (*sa)->sa.sa_family) {
+ *sock = i;
+ break;
+ }
+ }
+ }
+}
+
+static void choose_broadcast_address(const node_t *n, const sockaddr_t **sa, int *sock) {
+ static sockaddr_t broadcast_ipv4 = {
+ .in = {
+ .sin_family = AF_INET,
+ .sin_addr.s_addr = -1,
+ }
+ };
+
+ static sockaddr_t broadcast_ipv6 = {
+ .in6 = {
+ .sin6_family = AF_INET6,
+ .sin6_addr.s6_addr[0x0] = 0xff,
+ .sin6_addr.s6_addr[0x1] = 0x02,
+ .sin6_addr.s6_addr[0xf] = 0x01,
+ }
+ };
+
+ *sock = rand() % listen_sockets;
+
+ if(listen_socket[*sock].sa.sa.sa_family == AF_INET6) {
+ broadcast_ipv6.in6.sin6_port = n->prevedge->address.in.sin_port;
+ broadcast_ipv6.in6.sin6_scope_id = listen_socket[*sock].sa.in6.sin6_scope_id;
+ *sa = &broadcast_ipv6;
+ } else {
+ broadcast_ipv4.in.sin_port = n->prevedge->address.in.sin_port;
+ *sa = &broadcast_ipv4;
+ }
+}
+