diff --git a/src/network/connection.cpp b/src/network/connection.cpp index 7b8bb9166..2c6bde456 100644 --- a/src/network/connection.cpp +++ b/src/network/connection.cpp @@ -1551,29 +1551,22 @@ u16 Connection::createPeer(Address& sender, MTProtocols protocol, int fd) { // Somebody wants to make a new connection - // Get a unique peer id (2 or higher) - session_t peer_id_new = m_next_remote_peer_id; - u16 overflow = MAX_UDP_PEERS; + // Get a unique peer id + const session_t minimum = 2; + const session_t overflow = MAX_UDP_PEERS; /* Find an unused peer id */ + MutexAutoLock lock(m_peers_mutex); - bool out_of_ids = false; - for(;;) { - // Check if exists + session_t peer_id_new; + for (int tries = 0; tries < 100; tries++) { + peer_id_new = myrand_range(minimum, overflow - 1); if (m_peers.find(peer_id_new) == m_peers.end()) - break; - // Check for overflow - if (peer_id_new == overflow) { - out_of_ids = true; - break; - } - peer_id_new++; } - - if (out_of_ids) { + if (m_peers.find(peer_id_new) != m_peers.end()) { errorstream << getDesc() << " ran out of peer ids" << std::endl; return PEER_ID_INEXISTENT; } @@ -1585,8 +1578,6 @@ u16 Connection::createPeer(Address& sender, MTProtocols protocol, int fd) m_peers[peer->id] = peer; m_peer_ids.push_back(peer->id); - m_next_remote_peer_id = (peer_id_new +1 ) % MAX_UDP_PEERS; - LOG(dout_con << getDesc() << "createPeer(): giving peer_id=" << peer_id_new << std::endl); diff --git a/src/network/connection.h b/src/network/connection.h index e8451e3d5..e23cf954c 100644 --- a/src/network/connection.h +++ b/src/network/connection.h @@ -793,8 +793,6 @@ private: u32 m_bc_receive_timeout = 0; bool m_shutting_down = false; - - session_t m_next_remote_peer_id = 2; }; } // namespace diff --git a/src/unittest/test_connection.cpp b/src/unittest/test_connection.cpp index 04fea90d6..ce7464fec 100644 --- a/src/unittest/test_connection.cpp +++ b/src/unittest/test_connection.cpp @@ -245,7 +245,7 @@ void TestConnection::testConnectSendReceive() UASSERT(hand_client.last_id == 1); // Server should have the client UASSERT(hand_server.count == 1); - UASSERT(hand_server.last_id == 2); + UASSERT(hand_server.last_id >= 2); //sleep_ms(50); @@ -300,7 +300,7 @@ void TestConnection::testConnectSendReceive() UASSERT(memcmp(*sentdata, *recvdata, recvdata.getSize()) == 0); } - session_t peer_id_client = 2; + const session_t peer_id_client = hand_server.last_id; /* Send a large packet */ @@ -374,5 +374,5 @@ void TestConnection::testConnectSendReceive() UASSERT(hand_client.count == 1); UASSERT(hand_client.last_id == 1); UASSERT(hand_server.count == 1); - UASSERT(hand_server.last_id == 2); + UASSERT(hand_server.last_id >= 2); }