From 14c7500d9d149ce24f624a3db5092a05e4e83ae4 Mon Sep 17 00:00:00 2001 From: Renato Machado Date: Fri, 20 Oct 2023 14:24:18 -0300 Subject: [PATCH] improve: ip cache (#1691) The getIP is used a lot in the project and is a value that doesn't change, so we can cache it to avoid unnecessary lock. --- src/server/network/connection/connection.cpp | 12 +++++++----- src/server/network/connection/connection.hpp | 1 + 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/src/server/network/connection/connection.cpp b/src/server/network/connection/connection.cpp index 204ff83834e..8e637c053ee 100644 --- a/src/server/network/connection/connection.cpp +++ b/src/server/network/connection/connection.cpp @@ -54,6 +54,7 @@ void Connection::close(bool force) { ConnectionManager::getInstance().releaseConnection(shared_from_this()); std::lock_guard lockClass(connectionLock); + ip = 0; if (connectionState == CONNECTION_STATE_CLOSED) { return; } @@ -319,16 +320,17 @@ void Connection::internalWorker() { } uint32_t Connection::getIP() { + if (ip != 1) { + return ip; + } + std::lock_guard lockClass(connectionLock); // IP-address is expressed in network byte order std::error_code error; const asio::ip::tcp::endpoint endpoint = socket.remote_endpoint(error); - if (error) { - return 0; - } - - return htonl(endpoint.address().to_v4().to_ulong()); + ip = error ? 0 : htonl(endpoint.address().to_v4().to_uint()); + return ip; } void Connection::internalSend(const OutputMessage_ptr &outputMessage) { diff --git a/src/server/network/connection/connection.hpp b/src/server/network/connection/connection.hpp index c240046a01c..3a80bf6ca54 100644 --- a/src/server/network/connection/connection.hpp +++ b/src/server/network/connection/connection.hpp @@ -101,6 +101,7 @@ class Connection : public std::enable_shared_from_this { time_t timeConnected; uint32_t packetsSent = 0; + uint32_t ip = 1; std::underlying_type_t connectionState = CONNECTION_STATE_OPEN; bool receivedFirst = false;