1

I'm currently working on a UDP server. I want to redirect all incoming packets to the connected clients by using the ip address and port. My current way of doing it looks like this:

class Connection;
typedef std::map<unsigned short, Connection*> PortMap;
typedef std::map<unsigned int, PortMap> AddressMap;

So I'm basically using two maps. The second one contains a map of all the ports using an ipv4 address(unsigned int) as a key. The PortMap uses the port as the key and it contains a pointer to the Connection class(the clients).

I speed tested it by accessing 64 clients using randomly generated ips and ports and it took ~ (EDIT : 0.4 milliseconds) to access 64 different clients 64 times. I don't know really if it's slow or not. Of course it depends on the system I'm running the test on.

Here's how I'm accessing the client using the address:

Client * GetClient(Address address)
{
    AddressMap::iterator ipIt;
    PortMap::iterator portIt;
    unsigned int ip = address.GetAddress();
    unsigned short port = address.GetPort();

    /// Does the ip exist?
    if((ipIt = clientAddresses.find(ip)) == clientAddresses.end())
    {
        return NULL;
    }

    /// Does the port exist?
    if(clientAddresses[ip].find(port) == clientAddresses[ip].end())
    {   
        return NULL;
    }

    return clientAddresses[ip][port];
}

Does anyone know another faster way of doing it?

4

2 回答 2

0

64 次访问需要 400 毫秒的地图听起来非常慢……检查你的测量结果。您的映射可能应该基于 IP 和端口的组合(不是单独的),因为 NAT 可以组合特定 IP 下的客户端。

于 2012-11-14T15:43:39.247 回答
0

也许将IP和端口结合起来会更好..

端口 < 65535。您可以获得密钥:IP * 65535 + 端口,它对于所有端口和 IP 都是唯一的。

关于速度:比如我们有N个IP,每个IP有M个端口。

搜索地图具有高效的 N log(N),因此您的搜索需要 N*M*log(N)*log(M)。如果将 IP 和端口合二为一,则效率为 N*M*log(N*M)。log(N*M) = log(N)+log(M) < log(N)*log(M),对于大 N,M..

所以,我认为它会更好。

于 2012-11-14T16:27:30.587 回答