add 'network.find_free_port' function
This commit is contained in:
@@ -40,6 +40,8 @@ namespace network {
|
||||
int port,
|
||||
const ServerDatagramCallback& handler
|
||||
);
|
||||
|
||||
int find_free_port();
|
||||
}
|
||||
|
||||
|
||||
@@ -90,6 +92,10 @@ Server* Network::getServer(u64id_t id, bool includePrivate) const {
|
||||
return found->second.get();
|
||||
}
|
||||
|
||||
int Network::findFreePort() const {
|
||||
return find_free_port();
|
||||
}
|
||||
|
||||
u64id_t Network::connectTcp(
|
||||
const std::string& address,
|
||||
int port,
|
||||
|
||||
@@ -88,6 +88,8 @@ namespace network {
|
||||
[[nodiscard]] Connection* getConnection(u64id_t id, bool includePrivate);
|
||||
[[nodiscard]] Server* getServer(u64id_t id, bool includePrivate) const;
|
||||
|
||||
int findFreePort() const;
|
||||
|
||||
u64id_t connectTcp(
|
||||
const std::string& address,
|
||||
int port,
|
||||
|
||||
@@ -443,6 +443,7 @@ public:
|
||||
closesocket(descriptor);
|
||||
throw std::runtime_error("could not bind port "+std::to_string(port));
|
||||
}
|
||||
port = ntohs(address.sin_port);
|
||||
logger.info() << "opened server at port " << port;
|
||||
auto server =
|
||||
std::make_shared<SocketTcpServer>(id, network, descriptor, port);
|
||||
@@ -721,4 +722,24 @@ namespace network {
|
||||
) {
|
||||
return SocketUdpServer::openServer(id, network, port, handler);
|
||||
}
|
||||
|
||||
int find_free_port() {
|
||||
SOCKET descriptor = socket(AF_INET, SOCK_STREAM, 0);
|
||||
if (descriptor == -1) {
|
||||
return -1;
|
||||
}
|
||||
sockaddr_in address;
|
||||
address.sin_family = AF_INET;
|
||||
address.sin_addr.s_addr = INADDR_ANY;
|
||||
address.sin_port = 0;
|
||||
if (bind(descriptor, (sockaddr*)&address, sizeof(address)) < 0) {
|
||||
closesocket(descriptor);
|
||||
return -1;
|
||||
}
|
||||
socklen_t len = sizeof(address);
|
||||
getsockname(descriptor, (sockaddr*)&address, &len);
|
||||
int port = ntohs(address.sin_port);
|
||||
closesocket(descriptor);
|
||||
return port;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user