+static void adapt_socket(const sockaddr_t *sa, int *sock) {
+ /* 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_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;
+ }
+
+ adapt_socket(*sa, sock);
+}
+
+static void choose_local_address(const node_t *n, const sockaddr_t **sa, int *sock) {
+ *sa = NULL;
+
+ /* Pick one of the edges from this node at random, then use its local address. */
+
+ 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;
+ break;
+ }
+ }
+
+ if (candidate && candidate->local_address.sa.sa_family) {
+ *sa = &candidate->local_address;
+ *sock = rand() % listen_sockets;
+ adapt_socket(*sa, sock);
+ }
+}
+