From 0b7f4a5547b102cd20b31a2b204ba20fc4dd635d Mon Sep 17 00:00:00 2001 From: Tristan Stenner Date: Sat, 24 Jul 2021 14:26:15 +0200 Subject: [PATCH] `allow_random_ports`: Let the OS find an open port instead of trying some random ports --- src/socket_utils.cpp | 27 ++++++++++----------------- 1 file changed, 10 insertions(+), 17 deletions(-) diff --git a/src/socket_utils.cpp b/src/socket_utils.cpp index b329ea06..2c409972 100644 --- a/src/socket_utils.cpp +++ b/src/socket_utils.cpp @@ -23,32 +23,25 @@ uint16_t bind_port_in_range_(Socket &sock, Protocol protocol) { if (!ec) return port; } if (cfg->allow_random_ports()) { - for (int k = 0; k < 100; ++k) { - uint16_t port = 1025 + rand() % 64000; - sock.bind(typename Protocol::endpoint(protocol, port), ec); - if (ec == lslboost::system::errc::address_in_use) continue; - if (!ec) return port; - } + // bind to port 0, i.e. let the operating system select a free port + sock.bind(typename Protocol::endpoint(protocol, 0), ec); + // query and return the port the socket was bound to + if (!ec) return sock.local_endpoint().port(); } - return 0; + throw std::runtime_error( + "All local ports were found occupied. You may have more open outlets on this machine " + "than your PortRange setting allows (see " + "https://labstreaminglayer.readthedocs.io/info/network-connectivity.html" + ") or you have a problem with your network configuration."); } -const std::string all_ports_bound_msg( - "All local ports were found occupied. You may have more open outlets on this machine than your " - "PortRange setting allows (see " - "https://labstreaminglayer.readthedocs.io/info/network-connectivity.html" - ") or you have a problem with your network configuration."); - uint16_t lsl::bind_port_in_range(asio::ip::udp::socket &sock, asio::ip::udp protocol) { - uint16_t port = bind_port_in_range_(sock, protocol); - if (!port) throw std::runtime_error(all_ports_bound_msg); - return port; + return bind_port_in_range_(sock, protocol); } uint16_t lsl::bind_and_listen_to_port_in_range( asio::ip::tcp::acceptor &acc, asio::ip::tcp protocol, int backlog) { uint16_t port = bind_port_in_range_(acc, protocol); - if (!port) throw std::runtime_error(all_ports_bound_msg); acc.listen(backlog); return port; }