Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 10 additions & 17 deletions src/socket_utils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}