Ns3 Projects for B.E/B.Tech M.E/M.Tech PhD Scholars.  Phone-Number:9790238391   E-mail: ns3simulation@gmail.com

How to Implement least cost routing in ns3

To implement least cost routing in ns3, we need to follow several steps to calculate the least cost path between the nodes for that a custom routing protocol has to be created. The cost can be defined based on various metrics such as hop count, delay, bandwidth, or any combination of these.

The steps given below will help to implement the least cost routing in ns-3:

Step-by-Step Guide to Implement least cost routing in ns3:

  1. Set Up ns-3 Environment: Make sure that ns3 is installed the system.
  2. Include Necessary Libraries: The required ns3 libraries need to be included in the script.
  3. Define Network Topology: Create the nodes and links for your network topology.
  4. Install Internet Stack: Install the Internet stack on the nodes.
  5. Implement the Least Cost Routing Protocol: Create a custom routing protocol class that calculates the least cost paths using an appropriate algorithm (e.g., Dijkstra’s algorithm).
  6. Integrate the Custom Routing Protocol: Integrate the custom routing protocol into the ns-3 stack.
  7. Set Up Applications: Install applications to generate traffic and test the routing.
  8. Run the Simulation: Configure the simulation parameters and run it.

Example Implementation in C++

Here’s a detailed example to implement a least cost routing protocol in ns-3:

  1. Include Libraries:

#include “ns3/core-module.h”

#include “ns3/network-module.h”

#include “ns3/internet-module.h”

#include “ns3/point-to-point-module.h”

#include “ns3/applications-module.h”

#include “ns3/ipv4-routing-protocol.h”

#include “ns3/ipv4-list-routing-helper.h”

  1. Define Network Topology:

using namespace ns3;

int main(int argc, char *argv[]) {

CommandLine cmd;

cmd.Parse(argc, argv);

NodeContainer nodes;

nodes.Create(4);

PointToPointHelper pointToPoint;

pointToPoint.SetDeviceAttribute(“DataRate”, StringValue(“5Mbps”));

pointToPoint.SetChannelAttribute(“Delay”, StringValue(“2ms”));

NetDeviceContainer devices01, devices12, devices23, devices30;

devices01 = pointToPoint.Install(nodes.Get(0), nodes.Get(1)));

devices12 = pointToPoint.Install(nodes.Get(1), nodes.Get(2)));

devices23 = pointToPoint.Install(nodes.Get(2), nodes.Get(3)));

devices30 = pointToPoint.Install(nodes.Get(3), nodes.Get(0)));

InternetStackHelper stack;

stack.Install(nodes);

Ipv4AddressHelper address;

address.SetBase(“10.1.1.0”, “255.255.255.0”);

Ipv4InterfaceContainer interfaces01 = address.Assign(devices01);

address.SetBase(“10.1.2.0”, “255.255.255.0”);

Ipv4InterfaceContainer interfaces12 = address.Assign(devices12);

address.SetBase(“10.1.3.0”, “255.255.255.0”);

Ipv4InterfaceContainer interfaces23 = address.Assign(devices23);

address.SetBase(“10.1.4.0”, “255.255.255.0”);

Ipv4InterfaceContainer interfaces30 = address.Assign(devices30);

  1. Implement the Least Cost Routing Protocol:
  • Create a new header file least-cost-routing.h:

#ifndef LEAST_COST_ROUTING_H

#define LEAST_COST_ROUTING_H

#include “ns3/ipv4-routing-protocol.h”

#include “ns3/ipv4.h”

#include “ns3/net-device.h”

#include “ns3/ptr.h”

#include “ns3/socket.h”

#include <vector>

#include <map>

namespace ns3 {

class LeastCostRouting : public Ipv4RoutingProtocol {

public:

static TypeId GetTypeId(void);

LeastCostRouting();

virtual ~LeastCostRouting();

virtual Ptr<Ipv4Route> RouteOutput(

Ptr<Packet> p, const Ipv4Header &header,

Ptr<NetDevice> oif, Socket::SocketErrno &sockerr);

virtual bool RouteInput(

Ptr<const Packet> p, const Ipv4Header &header,

Ptr<const NetDevice> idev,

UnicastForwardCallback ucb, MulticastForwardCallback mcb,

LocalDeliverCallback lcb, ErrorCallback ecb);

virtual void NotifyInterfaceUp(uint32_t interface);

virtual void NotifyInterfaceDown(uint32_t interface);

virtual void NotifyAddAddress(uint32_t interface,  Ipv4InterfaceAddress address);

virtual void NotifyRemoveAddress(uint32_t interface,Ipv4InterfaceAddress address);

virtual void SetIpv4(Ptr<Ipv4> ipv4);

void Start();

private:

void CalculateLeastCostPaths();

void BroadcastRoutingUpdates();

void ReceiveRoutingUpdates(Ptr<Socket> socket);

Ptr<Ipv4> m_ipv4;

std::map<Ipv4Address, uint32_t> m_costVector;

std::map<Ipv4Address, Ipv4Address> m_nextHop;

std::map<uint32_t, Ptr<Socket>> m_socketMap;

Time m_updateInterval;

EventId m_updateEvent;

};

}

#endif // LEAST_COST_ROUTING_H

Create the corresponding implementation file least-cost-routing.cc:

#include “least-cost-routing.h”

#include “ns3/log.h”

#include “ns3/ipv4-routing-table-entry.h”

#include “ns3/simulator.h”

#include “ns3/inet-socket-address.h”

namespace ns3 {

NS_LOG_COMPONENT_DEFINE(“LeastCostRouting”);

NS_OBJECT_ENSURE_REGISTERED(LeastCostRouting);

 

TypeId LeastCostRouting::GetTypeId(void) {

static TypeId tid = TypeId(“ns3::LeastCostRouting”)

.SetParent<Ipv4RoutingProtocol>()

.SetGroupName(“Internet”)

.AddConstructor<LeastCostRouting>();

return tid;

}

LeastCostRouting::LeastCostRouting() : m_updateInterval(Seconds(5)) {

NS_LOG_FUNCTION(this);

Simulator::Schedule(Seconds(1.0), &LeastCostRouting::Start, this);

}

LeastCostRouting::~LeastCostRouting() {

NS_LOG_FUNCTION(this);

}

void LeastCostRouting::SetIpv4(Ptr<Ipv4> ipv4) {

NS_LOG_FUNCTION(this << ipv4);

m_ipv4 = ipv4;

}

void LeastCostRouting::Start() {

NS_LOG_FUNCTION(this);

CalculateLeastCostPaths();

BroadcastRoutingUpdates();

m_updateEvent = Simulator::Schedule(m_updateInterval, &LeastCostRouting::Start, this);

}

void LeastCostRouting::CalculateLeastCostPaths() {

NS_LOG_FUNCTION(this);

 

// Initialize costs and next hops

for (uint32_t i = 0; i < m_ipv4->GetNInterfaces(); ++i) {

Ipv4Address addr = m_ipv4->GetAddress(i, 0).GetLocal();

m_costVector[addr] = (addr == m_ipv4->GetAddress(1, 0).GetLocal()) ? 0 : UINT32_MAX;

m_nextHop[addr] = Ipv4Address::GetAny();

}

// Dijkstra’s algorithm to calculate least cost paths

for (uint32_t i = 0; i < m_ipv4->GetNInterfaces(); ++i) {

Ipv4Address addr = m_ipv4->GetAddress(i, 0).GetLocal();

for (uint32_t j = 0; j < m_ipv4->GetNInterfaces(); ++j) {

Ipv4Address neighbor = m_ipv4->GetAddress(j, 0).GetLocal();

uint32_t linkCost = 1; // Example link cost, modify as needed

if (m_costVector[addr] > m_costVector[neighbor] + linkCost) {

m_costVector[addr] = m_costVector[neighbor] + linkCost;

m_nextHop[addr] = neighbor;

}

}

}

}

void LeastCostRouting::BroadcastRoutingUpdates() {

NS_LOG_FUNCTION(this);

Ptr<Packet> packet = Create<Packet>();

for (auto it : m_costVector) {

Ipv4Address addr = it.first;

uint32_t cost = it.second;

packet->AddHeader(Ipv4Header(addr, Ipv4Address::GetBroadcast(), cost, 0));

}

for (uint32_t i = 0; i < m_ipv4->GetNInterfaces(); ++i) {

Ptr<Socket> socket = m_socketMap[i];

socket->SendTo(packet, 0, InetSocketAddress(Ipv4Address::GetBroadcast(), 80));

}

}

void LeastCostRouting::ReceiveRoutingUpdates(Ptr<Socket> socket) {

NS_LOG_FUNCTION(this);

Ptr<Packet> packet = socket->Recv();

Ipv4Header header;

packet->RemoveHeader(header);

Ipv4Address addr = header.GetDestination();

uint32_t cost = header.GetIdentification();

if (m_costVector[addr] > cost) {

m_costVector[addr] = cost;

m_nextHop[addr] = header.GetSource();

}

}

Ptr<Ipv4Route> LeastCostRouting::RouteOutput(

Ptr<Packet> p, const Ipv4Header &header, Ptr<NetDevice> oif,

Socket::SocketErrno &sockerr) {

NS_LOG_FUNCTION(this << p << header << oif << sockerr);

Ipv4Address dest = header.GetDestination();

if (m_nextHop.find(dest) == m_nextHop.end()) {

sockerr = Socket::ERROR_NOROUTETOHOST;

return 0;

}

Ptr<Ipv4Route> route = Create<Ipv4Route>();

route->SetDestination(dest);

route->SetGateway(m_nextHop[dest]);

route->SetOutputDevice(oif);

return route;

}

bool LeastCostRouting::RouteInput(

Ptr<const Packet> p, const Ipv4Header &header,

Ptr<const NetDevice> idev, UnicastForwardCallback ucb,

MulticastForwardCallback mcb, LocalDeliverCallback lcb,

ErrorCallback ecb) {

NS_LOG_FUNCTION(this << p << header << idev << ucb << mcb  << lcb << ecb);

Ipv4Address dest = header.GetDestination();

if (dest == m_ipv4->GetAddress(1, 0).GetLocal()) {

lcb(p, header, idev);

return true;

}

if (m_nextHop.find(dest) == m_nextHop.end()) {

ecb(p, header, Socket::ERROR_NOROUTETOHOST);

return false;

}

Ptr<Ipv4Route> route = Create<Ipv4Route>();

route->SetDestination(dest);

route->SetGateway(m_nextHop[dest]);

route->SetOutputDevice(idev);

ucb(route, p, header);

return true;

}

void LeastCostRouting::NotifyInterfaceUp(uint32_t interface) {

NS_LOG_FUNCTION(this << interface);

Ptr<Socket>socket=Socket::CreateSocket(GetObject<Node>(), TypeId::LookupByName(“ns3::UdpSocketFactory”));

socket->SetAllowBroadcast(true);

socket->BindToNetDevice(m_ipv4->GetNetDevice(interface));

socket->Bind(InetSocketAddress(Ipv4Address::GetAny(), 80));

socket->SetRecvCallback(MakeCallback(&LeastCostRouting::ReceiveRoutingUpdates, this));

m_socketMap[interface] = socket;

}

void LeastCostRouting::NotifyInterfaceDown(uint32_t interface) {

NS_LOG_FUNCTION(this << interface);

m_socketMap[interface]->Close();

m_socketMap.erase(interface);

}

void LeastCostRouting::NotifyAddAddress(uint32_t interface,

Ipv4InterfaceAddress address) {

NS_LOG_FUNCTION(this << interface << address);

}

void LeastCostRouting::NotifyRemoveAddress(uint32_t interface,

Ipv4InterfaceAddress address) {

NS_LOG_FUNCTION(this << interface << address);

}

}

  1. Integrate the Custom Routing Protocol:

#include “least-cost-routing.h”

int main(int argc, char *argv[]) {

CommandLine cmd;

cmd.Parse(argc, argv);

NodeContainer nodes;

nodes.Create(4);

PointToPointHelper pointToPoint;

pointToPoint.SetDeviceAttribute(“DataRate”, StringValue(“5Mbps”));

pointToPoint.SetChannelAttribute(“Delay”, StringValue(“2ms”));

NetDeviceContainer devices01, devices12, devices23, devices30;

devices01 = pointToPoint.Install(nodes.Get(0), nodes.Get(1)));

devices12 = pointToPoint.Install(nodes.Get(1), nodes.Get(2)));

devices23 = pointToPoint.Install(nodes.Get(2), nodes.Get(3)));

devices30 = pointToPoint.Install(nodes.Get(3), nodes.Get(0)));

InternetStackHelper stack;

LeastCostRoutingHelper leastCostRouting;

Ipv4ListRoutingHelper list;

list.Add(leastCostRouting, 0);

stack.SetRoutingHelper(list);

stack.Install(nodes);

Ipv4AddressHelper address;

address.SetBase(“10.1.1.0”, “255.255.255.0”);

address.Assign(devices01);

address.SetBase(“10.1.2.0”, “255.255.255.0”);

address.Assign(devices12);

address.SetBase(“10.1.3.0”, “255.255.255.0”);

address.Assign(devices23);

address.SetBase(“10.1.4.0”, “255.255.255.0”);

address.Assign(devices30);

// Set up applications

uint16_t port = 9;

UdpEchoServerHelper server(port);

ApplicationContainer apps = server.Install(nodes.Get(3));

apps.Start(Seconds(1.0));

apps.Stop(Seconds(10.0));

UdpEchoClientHelper client(address.GetAddress(3), port);

client.SetAttribute(“MaxPackets”, UintegerValue(1));

client.SetAttribute(“Interval”, TimeValue(Seconds(1.0)));

client.SetAttribute(“PacketSize”, UintegerValue(1024));

apps = client.Install(nodes.Get(0));

apps.Start(Seconds(2.0));

apps.Stop(Seconds(10.0));

Simulator::Run();

Simulator::Destroy();

return 0;

}

Explanation

  1. Network Topology: The code sets up a network topology with four nodes connected in a ring.
  2. Least Cost Routing Protocol: A custom least cost routing protocol class (LeastCostRouting) is implemented. This class calculates the least cost paths using a chosen metric (e.g., hop count).
  3. Least Cost Path Calculation: The CalculateLeastCostPaths method initializes and computes the least cost paths using Dijkstra’s algorithm or another appropriate algorithm.
  4. Routing Updates: The BroadcastRoutingUpdates method broadcasts routing updates to neighbors, and ReceiveRoutingUpdates handles incoming updates.
  5. Route Input and Output: The RouteInput and RouteOutput methods handle packet routing using the computed least cost paths.
  6. Integrate Custom Routing Protocol: The custom routing protocol is integrated into the ns3 stack using the LeastCostRoutingHelper.
  7. Applications: UdpEchoServer and UdpEchoClient applications are set up to test the routing.
  1. Running the Code
  1. Save the script to a file, for example, least-cost-routing.cc.
  2. Compile the script using the ns3 build system

./waf configure –enable-examples

./waf build

./waf –run scratch/least-cost-routing

From the implementation process of least cost routing, we had learnt that custom routing protocol calculates the least cost path between the nodes in the network by using the appropriate algorithm for the simulation process.

Least cost routing in ns3 with ideal simulation results are granted by ns3simulation.com team.