+#define IS_IPV4(addr) (((const ip_address *) addr)->family == AF_INET)
+
+/* Compare two IP addresses by family, giving preference to the IPv4
+ address (sorting it first). In other words, return -1 if ADDR1 is
+ IPv4 and ADDR2 is IPv6, +1 if ADDR1 is IPv6 and ADDR2 is IPv4, and
+ 0 otherwise.
+
+ This is intended to be used as the comparator arg to a qsort-like
+ sorting function, which is why it accepts generic pointers. */
+
+static int
+cmp_prefer_ipv4 (const void *addr1, const void *addr2)
+{
+ return !IS_IPV4 (addr1) - !IS_IPV4 (addr2);
+}
+
+#define IS_IPV6(addr) (((const ip_address *) addr)->family == AF_INET6)
+
+/* Like the above, but give preference to the IPv6 address. */
+
+static int
+cmp_prefer_ipv6 (const void *addr1, const void *addr2)
+{
+ return !IS_IPV6 (addr1) - !IS_IPV6 (addr2);
+}
+