+ const in_port_t default_port= in_port_t(-1);
+
+ int retries= 1024;
+
+ in_port_t ret_port;
+ while (--retries)
+ {
+ ret_port= default_port;
+ int sd;
+ if ((sd= socket(AF_INET, SOCK_STREAM, 0)) != SOCKET_ERROR)
+ {
+ int optval= 1;
+ if (setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)) != SOCKET_ERROR)
+ {
+ struct sockaddr_in sin;
+ sin.sin_port= 0;
+ sin.sin_addr.s_addr= 0;
+ sin.sin_addr.s_addr= INADDR_ANY;
+ sin.sin_family= AF_INET;
+
+ int bind_ret;
+ do
+ {
+ if ((bind_ret= bind(sd, (struct sockaddr *)&sin, sizeof(struct sockaddr_in) )) != SOCKET_ERROR)
+ {
+ socklen_t addrlen= sizeof(sin);
+
+ if (getsockname(sd, (struct sockaddr *)&sin, &addrlen) != -1)
+ {
+ ret_port= sin.sin_port;
+ }
+ }
+ else
+ {
+ if (errno != EADDRINUSE)
+ {
+ Error << strerror(errno);
+ }
+ }
+
+ if (errno == EADDRINUSE)
+ {
+ libtest::dream(2, 0);
+ }
+ } while (bind_ret == -1 and errno == EADDRINUSE);
+
+ all_socket_fd._pair.push_back(std::make_pair(sd, ret_port));
+ }
+ else
+ {
+ Error << strerror(errno);
+ }
+ }
+ else
+ {
+ Error << strerror(errno);
+ }
+
+ if (ret_port == default_port)
+ {
+ Error << "no ret_port set:" << strerror(errno);
+ }
+ else if (ret_port > 1024 and ret_port != all_socket_fd.last_port)
+ {
+ break;
+ }
+ }
+
+ // We handle the case where if we max out retries, we still abort.
+ if (retries == 0)
+ {
+ FATAL("No port could be found, exhausted retry");
+ }
+
+ if (ret_port == 0)
+ {
+ FATAL("No port could be found");
+ }
+
+ if (ret_port == default_port)