Skip to content

Commit cdce3aa

Browse files
committed
Avoid infinite loop if no socket can be bound
1 parent 4b10a83 commit cdce3aa

File tree

1 file changed

+15
-7
lines changed

1 file changed

+15
-7
lines changed

src/socket_utils.h

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -20,15 +20,19 @@ namespace lsl {
2020
} catch (lslboost::system::system_error &) { /* port occupied */ }
2121
}
2222
if (api_config::get_instance()->allow_random_ports()) {
23-
while (true) {
23+
for (int k=0; k < 100; ++k) {
2424
uint16_t port = 1025 + rand()%64000;
2525
try {
2626
sock.bind(typename Protocol::endpoint(protocol,port));
2727
return port;
2828
} catch (lslboost::system::system_error &) { /* port occupied */ }
2929
}
30-
} else
31-
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 Network Connectivity in the LSL wiki) or you have a problem with your network configuration.");
30+
}
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) or you "
35+
"have a problem with your network configuration.");
3236
}
3337

3438
/// Bind to and listen at a socket (or acceptor) on a free port in the configured port range or throw an error otherwise.
@@ -37,21 +41,25 @@ namespace lsl {
3741
for (int k=0,e=api_config::get_instance()->port_range(); k<e; k++) {
3842
try {
3943
sock.bind(typename Protocol::endpoint(protocol,(uint16_t)(k + api_config::get_instance()->base_port())));
40-
sock.listen(backlog);
44+
sock.listen(backlog);
4145
return k + api_config::get_instance()->base_port();
4246
} catch (lslboost::system::system_error &) { /* port occupied */ }
4347
}
4448
if (api_config::get_instance()->allow_random_ports()) {
45-
while (true) {
49+
for (int k = 0; k < 100; ++k) {
4650
uint16_t port = 1025 + rand()%64000;
4751
try {
4852
sock.bind(typename Protocol::endpoint(protocol,port));
4953
sock.listen(backlog);
5054
return port;
5155
} catch (lslboost::system::system_error &) { /* port occupied */ }
5256
}
53-
} else
54-
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 Network Connectivity in the LSL wiki) or you have a problem with your network configuration.");
57+
}
58+
throw std::runtime_error(
59+
"All local ports were found occupied. You may have more open outlets on this machine "
60+
"than your PortRange setting allows (see "
61+
"https://labstreaminglayer.readthedocs.io/info/network-connectivity.html) or you "
62+
"have a problem with your network configuration.");
5563
}
5664

5765
/// Measure the endian conversion performance of this machine.

0 commit comments

Comments
 (0)