+#ifdef HAVE_RES_QUERY
+#define DNSBUFSIZ (64*1024)
+#define MAXHOST 254 /* RFC 1034, max length is 253 chars */
+typedef struct srv_record {
+ u_short priority;
+ u_short weight;
+ u_short port;
+ char hostname[MAXHOST];
+} srv_record;
+
+/* Linear Congruential Generator - we don't need
+ * high quality randomness, and we don't want to
+ * interfere with anyone else's use of srand().
+ *
+ * The PRNG here cycles thru 941,955 numbers.
+ */
+static float srv_seed;
+
+static void srv_srand(int seed) {
+ srv_seed = (float)seed / (float)RAND_MAX;
+}
+
+static float srv_rand() {
+ float val = 9821.0 * srv_seed + .211327;
+ srv_seed = val - (int)val;
+ return srv_seed;
+}
+
+static int srv_cmp(const void *aa, const void *bb){
+ srv_record *a=(srv_record *)aa;
+ srv_record *b=(srv_record *)bb;
+ int i = a->priority - b->priority;
+ if (i) return i;
+ return b->weight - a->weight;
+}
+
+static void srv_shuffle(srv_record *a, int n) {
+ int i, j, total = 0, r, p;
+
+ for (i=0; i<n; i++)
+ total += a[i].weight;
+
+ /* all weights are zero, do a straight Fisher-Yates shuffle */
+ if (!total) {
+ while (n) {
+ srv_record t;
+ i = srv_rand() * n--;
+ t = a[n];
+ a[n] = a[i];
+ a[i] = t;
+ }
+ return;
+ }
+
+ /* Do a shuffle per RFC2782 Page 4 */
+ p = n;
+ for (i=0; i<n-1; i++) {
+ r = srv_rand() * total;
+ for (j=0; j<p; j++) {
+ r -= a[j].weight;
+ if (r <= 0) {
+ if (j) {
+ srv_record t = a[0];
+ a[0] = a[j];
+ a[j] = t;
+ }
+ total -= a[0].weight;
+ a++;
+ p--;
+ break;
+ }
+ }
+ }
+}
+#endif /* HAVE_RES_QUERY */
+