// networklayer.cc for the assignment 2. // Last modified 4/Sep/2006 Ahmet Sekercioglu #include #include #include "packet_m.h" class NetworkLayer : public cSimpleModule { private: int myAddress; bool router; typedef std::map RoutingTable; // destaddr --> port RoutingTable rtable; protected: virtual void initialize(); virtual void handleMessage(cMessage *msg); virtual void finish(); }; Define_Module(NetworkLayer); void NetworkLayer::initialize() { myAddress = parentModule()->par("address"); WATCH(myAddress); // Am I part of a router or not? if (strcmp("router", parentModule()->name()) == 0) { router = true; } else { router = false; } } void NetworkLayer::handleMessage(cMessage *msg) { Packet *pk = check_and_cast(msg); int destAddr = pk->getDestAddr(); if (destAddr == myAddress) { if (router) { // Routers don't have an application layer. ev << "Packet discarded: " << pk->name() << endl; delete pk; } else { ev << "Delivery of packet to higher layer: " << pk->name() << endl; send(pk,"localOut"); } return; } RoutingTable::iterator it = rtable.find(destAddr); if (it == rtable.end()) { ev << "Address " << destAddr << " unreachable, discarding packet " << pk->name() << endl; delete pk; return; } if (pk->getSrcAddr() == -1) { // Application layer has forwarded this packet to the network layer. char pkname[40]; sprintf(pkname,"pk-%d-to-%d", myAddress, pk->getDestAddr()); pk->setSrcAddr(myAddress); pk->setName(pkname); } int outGate = (*it).second; ev << simTime() << " Forwarding packet " << pk->name() << " on gate id = " << outGate << endl; pk->setHopCount(pk->getHopCount()+1); send(pk, outGate); } void NetworkLayer::finish() { RoutingTable::iterator it; int dest_address = (*it).first; int outGateId = (*it).second; ev << parentModule()->fullName() << " final routing table:" << endl; ev << " destination\tnext hop" << endl; ev << " address" << endl; ev << " -----------\t--------" << endl; for(it = rtable.begin(); it != rtable.end(); it++) { dest_address = (*it).first; outGateId = (*it).second; // (Keep network diagram close-by if you get confused about the following // information, observing the connections on the diagram will help.) // We will now follow the path to find the nextHopModule. // // OutGateId is the ID of the local gate connected to the // outputQueueModule. serverModule services the // outputQueueModule. serverModule is connected to the gate // connected to the nextHopModule towards the destination node // module. cGate *outGate = gate(outGateId); cModule *outputQueueModule = outGate->toGate()->ownerModule(); cModule *serverModule = outputQueueModule->gate("out")->toGate()->ownerModule(); cGate *parentModuleGate = serverModule->gate("out")->toGate(); cModule *nextHopModule = parentModuleGate->toGate()->ownerModule(); ev << " " << dest_address << "\t" << nextHopModule->fullName() << endl; } ev << " " << endl; }