Client bind to port 0 by default(dynamic) and reuse port YAZ-795
authorAdam Dickmeiss <adam@indexdata.dk>
Wed, 22 Oct 2014 17:11:17 +0000 (19:11 +0200)
committerAdam Dickmeiss <adam@indexdata.dk>
Wed, 22 Oct 2014 17:11:17 +0000 (19:11 +0200)
src/tcpip.c

index 6d00525..21fa041 100644 (file)
@@ -474,17 +474,33 @@ static struct addrinfo *create_net_socket(COMSTACK h)
                    IPPROTO_IPV6,
                    IPV6_V6ONLY, &sp->ipv6_only, sizeof(sp->ipv6_only)))
         return 0;
-    if (!tcpip_set_blocking(h, h->flags))
-        return 0;
     if (sp->bind_host)
     {
-        int r;
+        int r = -1;
         int ipv6_only = 0;
-        struct addrinfo *ai = tcpip_getaddrinfo(sp->bind_host, "210",
-                                                &ipv6_only);
+        struct addrinfo *ai;
+
+#ifndef WIN32
+        int one = 1;
+        if (setsockopt(h->iofile, SOL_SOCKET, SO_REUSEADDR, (char*)
+                       &one, sizeof(one)) < 0)
+        {
+            h->cerrno = CSYSERR;
+            return 0;
+        }
+#endif
+        ai = tcpip_getaddrinfo(sp->bind_host, "0", &ipv6_only);
         if (!ai)
             return 0;
-        r = bind(h->iofile, ai->ai_addr, ai->ai_addrlen);
+        {
+            struct addrinfo *a;
+            for (a = ai; a; a = a->ai_next)
+            {
+                r = bind(h->iofile, a->ai_addr, a->ai_addrlen);
+                if (!r)
+                    break;
+            }
+        }
         if (r)
         {
             int xerrno = errno;
@@ -497,6 +513,8 @@ static struct addrinfo *create_net_socket(COMSTACK h)
         }
         freeaddrinfo(ai);
     }
+    if (!tcpip_set_blocking(h, h->flags))
+        return 0;
     return ai;
 }