Skip to content

Commit 0b7f4a5

Browse files
committed
allow_random_ports: Let the OS find an open port instead of trying some random ports
1 parent 9ee5524 commit 0b7f4a5

File tree

1 file changed

+10
-17
lines changed

1 file changed

+10
-17
lines changed

src/socket_utils.cpp

Lines changed: 10 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -23,32 +23,25 @@ uint16_t bind_port_in_range_(Socket &sock, Protocol protocol) {
2323
if (!ec) return port;
2424
}
2525
if (cfg->allow_random_ports()) {
26-
for (int k = 0; k < 100; ++k) {
27-
uint16_t port = 1025 + rand() % 64000;
28-
sock.bind(typename Protocol::endpoint(protocol, port), ec);
29-
if (ec == lslboost::system::errc::address_in_use) continue;
30-
if (!ec) return port;
31-
}
26+
// bind to port 0, i.e. let the operating system select a free port
27+
sock.bind(typename Protocol::endpoint(protocol, 0), ec);
28+
// query and return the port the socket was bound to
29+
if (!ec) return sock.local_endpoint().port();
3230
}
33-
return 0;
31+
throw std::runtime_error(
32+
"All local ports were found occupied. You may have more open outlets on this machine "
33+
"than your PortRange setting allows (see "
34+
"https://labstreaminglayer.readthedocs.io/info/network-connectivity.html"
35+
") or you have a problem with your network configuration.");
3436
}
3537

36-
const std::string all_ports_bound_msg(
37-
"All local ports were found occupied. You may have more open outlets on this machine than your "
38-
"PortRange setting allows (see "
39-
"https://labstreaminglayer.readthedocs.io/info/network-connectivity.html"
40-
") or you have a problem with your network configuration.");
41-
4238
uint16_t lsl::bind_port_in_range(asio::ip::udp::socket &sock, asio::ip::udp protocol) {
43-
uint16_t port = bind_port_in_range_(sock, protocol);
44-
if (!port) throw std::runtime_error(all_ports_bound_msg);
45-
return port;
39+
return bind_port_in_range_(sock, protocol);
4640
}
4741

4842
uint16_t lsl::bind_and_listen_to_port_in_range(
4943
asio::ip::tcp::acceptor &acc, asio::ip::tcp protocol, int backlog) {
5044
uint16_t port = bind_port_in_range_(acc, protocol);
51-
if (!port) throw std::runtime_error(all_ports_bound_msg);
5245
acc.listen(backlog);
5346
return port;
5447
}

0 commit comments

Comments
 (0)