+#ifdef HAVE_RES_QUERY
+#define DNSBUFSIZ (64*1024)
+typedef struct srv_record {
+ u_short priority;
+ u_short weight;
+ u_short port;
+ char hostname[DNSBUFSIZ];
+} srv_record;
+
+
+static int srv_cmp(const void *aa, const void *bb){
+ srv_record *a=(srv_record *)aa;
+ srv_record *b=(srv_record *)bb;
+ u_long total;
+
+ if(a->priority < b->priority) {
+ return -1;
+ }
+ if(a->priority > b->priority) {
+ return 1;
+ }
+ if(a->priority == b->priority){
+ /* targets with same priority are in psudeo random order */
+ if (a->weight == 0 && b->weight == 0) {
+ if (rand() % 2) {
+ return -1;
+ } else {
+ return 1;
+ }
+ }
+ total = a->weight + b->weight;
+ if (rand() % total < a->weight) {
+ return -1;
+ } else {
+ return 1;
+ }
+ }
+}
+#endif /* HAVE_RES_QUERY */
+