Search code examples
omnet++inet

How to find out the number of received packets from each sender


In OMNET++ with INET framework, I want to find out how many packets are received from each sending node.I found the below code. Can anyone tell me what is function of "it->second++" command in below code?

std::map<L3Address, uint64_t> recPkt;
auto it = recPkt.find(senderAddr);
if (it == recPkt.end())
    recPkt[senderAddr] = 1;
else
    it->second++;

Also, can anyone suggest how to display the number of received packets per node.


Solution

  • it is an iterator to an element of std::map. Iterator is something like a pointer. it points to a pair: <L3Address, uint64_t>. Probably the address of sender is the first element of this pair, and the second one is the number of received packets.
    The first element of this pair may be obtained using it->first while the second via it->second. Operation recPkt.find(senderAddr) checks whether recPkt contains an entry with the address senderAddr:

    • if not, it points to recPkt.end(), then a new entry is created and 1 is set as value (because first packet has been just received),
    • if entry for senderAddr already exists, the second value of this element (counter) is incremented using it->second++

    To show current value of received packets to internal log window one may use:

    for (auto it : recPkt) {
       EV << "From address " << it.first << " received " << it.second << " packets." << std::endl;   
    }
    

    However, the better way is to write these values to statistics. The best place for it is a finish() method of your module:

    void YourModule::finish() {
       // ..
       for (auto it : recPkt) {
          std::string name = "Received packet from ";
          name += it.first.str(); // address
          recordScalar(name, it.second);  
        } 
    }
    

    Reference: C++ Reference, std::map

    EDIT

    One more thing. The declaration of recPkt i.e. line:

    std::map<L3Address, uint64_t> recPkt;
    

    must be in your class. recPkt cannot be declared just before use.