Merge branch 'main' into debugging-client

This commit is contained in:
MihailRis 2025-11-15 16:42:36 +03:00
commit 3725aacbb1
6 changed files with 48 additions and 0 deletions

View File

@ -132,3 +132,10 @@ network.get_total_upload() --> int
-- in bytes.
network.get_total_download() --> int
```
## Other
```lua
-- Looks for a free port to use.
network.find_free_port() --> int
```

View File

@ -197,3 +197,10 @@ network.get_total_upload() --> int
-- в байтах.
network.get_total_download() --> int
```
## Другое
```lua
-- Ищет свободный для использования порт.
network.find_free_port() --> int
```

View File

@ -409,6 +409,10 @@ static int l_get_total_download(lua::State* L, network::Network& network) {
return lua::pushinteger(L, network.getTotalDownload());
}
static int l_find_free_port(lua::State* L, network::Network& network) {
return lua::pushinteger(L, network.findFreePort());
}
static int l_set_nodelay(lua::State* L, network::Network& network) {
u64id_t id = lua::tointeger(L, 1);
bool noDelay = lua::toboolean(L, 2);
@ -534,6 +538,7 @@ const luaL_Reg networklib[] = {
{"__post", wrap<l_post>},
{"get_total_upload", wrap<l_get_total_upload>},
{"get_total_download", wrap<l_get_total_download>},
{"find_free_port", wrap<l_find_free_port>},
{"__pull_events", wrap<l_pull_events>},
{"__open_tcp", wrap<l_open_tcp>},
{"__open_udp", wrap<l_open_udp>},

View File

@ -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,

View File

@ -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,

View File

@ -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;
}
}