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

How to Implement leach routing in ns3

To implement LEACH (Low-Energy Adaptive Clustering Hierarchy) in ns3, we need to follow several steps. LEACH is mainly consists on wireless sensor networks to optimize energy usage for that a custom routing protocol has to be created to form clusters of nodes and elects cluster heads to aggregate and forward data to the base station.

The following steps will guide to implement LEACH routing in ns-3:

Step-by-Step Guide to Implement LEACH routing in ns3:

  1. Set Up ns3 Environment: Make sure ns3 is installed the system.
  2. Include Necessary Libraries: Required ns3 libraries need to be included in the script.
  3. Define Network Topology: Set up the network topology by creating the nodes.
  4. Implement the LEACH Routing Protocol: Create a custom routing protocol class that performs clustering and cluster head election.
  5. Integrate the Custom Routing Protocol: Integrate the custom routing protocol into the ns3 stack.
  6. Set Up Applications: Install applications to generate traffic and test the routing.
  7. Run the Simulation: Configure the simulation parameters and run it.

Example Implementation in C++

Here’s a detailed example to implement a LEACH 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/mobility-module.h”

  1. Define Network Topology:

using namespace ns3;

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

CommandLine cmd;

cmd.Parse(argc, argv);

NodeContainer nodes;

nodes.Create(10);

MobilityHelper mobility;

mobility.SetPositionAllocator(“ns3::GridPositionAllocator”,

“MinX”, DoubleValue(0.0),

“MinY”, DoubleValue(0.0),

“DeltaX”, DoubleValue(10.0),

“DeltaY”, DoubleValue(10.0),

“GridWidth”, UintegerValue(5),

“LayoutType”, StringValue(“RowFirst”));

mobility.SetMobilityModel(“ns3::ConstantPositionMobilityModel”);

mobility.Install(nodes);

InternetStackHelper stack;

stack.Install(nodes);

PointToPointHelper pointToPoint;

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

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

// In LEACH, direct connections are not used, so we skip setting up point-to-point links here.

Ipv4AddressHelper address;

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

// address.Assign(devices);  // Not needed as we don’t have point-to-point links.

  1. Implement the LEACH Routing Protocol:
  • Create a new header file leach-routing.h:

#ifndef LEACH_ROUTING_H

#define LEACH_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>

namespace ns3 {

class LeachRouting : public Ipv4RoutingProtocol {

public:

static TypeId GetTypeId(void);

LeachRouting();

virtual ~LeachRouting();

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 StartRound();

private:

void ElectClusterHeads();

void FormClusters();

void ScheduleNextRound();

Ptr<Ipv4> m_ipv4;

std::vector<uint32_t> m_clusterHeads;

std::map<uint32_t, uint32_t> m_nodeClusterMap;

Time m_roundInterval;

EventId m_roundEvent;

};

}

#endif // LEACH_ROUTING_H

Create the corresponding implementation file leach-routing.cc:

#include “leach-routing.h”

#include “ns3/log.h”

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

#include “ns3/simulator.h”

#include “ns3/random-variable-stream.h”

namespace ns3 {

NS_LOG_COMPONENT_DEFINE(“LeachRouting”);

NS_OBJECT_ENSURE_REGISTERED(LeachRouting);

TypeId LeachRouting::GetTypeId(void) {

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

.SetParent<Ipv4RoutingProtocol>()

.SetGroupName(“Internet”)

.AddConstructor<LeachRouting>();

return tid;

}

LeachRouting::LeachRouting() : m_roundInterval(Seconds(20)) {

NS_LOG_FUNCTION(this);

Simulator::Schedule(Seconds(1.0), &LeachRouting::StartRound, this);

}

LeachRouting::~LeachRouting() {

NS_LOG_FUNCTION(this);

}

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

NS_LOG_FUNCTION(this << ipv4);

m_ipv4 = ipv4;

}

void LeachRouting::StartRound() {

NS_LOG_FUNCTION(this);

ElectClusterHeads();

FormClusters();

ScheduleNextRound();

}

void LeachRouting::ElectClusterHeads() {

NS_LOG_FUNCTION(this);

m_clusterHeads.clear();

Ptr<UniformRandomVariable> rand = CreateObject<UniformRandomVariable>();

for (uint32_t i = 0; i < m_ipv4->GetObject<Node>()->GetNDevices(); ++i) {

if (rand->GetValue() < 0.1) {m_clusterHeads.push_back(i);

}

}

NS_LOG_INFO(“Cluster heads elected: ” << m_clusterHeads.size());

}

void LeachRouting::FormClusters() {

NS_LOG_FUNCTION(this);

m_nodeClusterMap.clear();

for (uint32_t i = 0; i < m_ipv4->GetObject<Node>()->GetNDevices(); ++i) {

if (std::find(m_clusterHeads.begin(), m_clusterHeads.end(), i) == m_clusterHeads.end()) {

// Assign node to the closest cluster head

uint32_t closestClusterHead = m_clusterHeads[0];

double minDistance = m_ipv4->GetObject<Node>()->GetDevice(i)->GetObject<MobilityModel>()->GetDistanceFrom(m_ipv4->GetObject<Node>()->GetDevice(closestClusterHead)->GetObject<MobilityModel>());

for (uint32_t ch : m_clusterHeads) {

double distance = m_ipv4->GetObject<Node>()->GetDevice(i)->GetObject<MobilityModel>()->GetDistanceFrom(m_ipv4->GetObject<Node>()->GetDevice(ch)->GetObject<MobilityModel>());

if (distance < minDistance) {

closestClusterHead = ch;

minDistance = distance;

}

}

m_nodeClusterMap[i] = closestClusterHead;

}

}

}

void LeachRouting::ScheduleNextRound() {

NS_LOG_FUNCTION(this);

m_roundEvent = Simulator::Schedule(m_roundInterval, &LeachRouting::StartRound, this);

}

Ptr<Ipv4Route> LeachRouting::RouteOutput(

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

Socket::SocketErrno &sockerr) {

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

// LEACH routing does not need to implement RouteOutput

return 0;

}

bool LeachRouting::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);

// Check if the packet is destined for this node

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

lcb(p, header, idev);

return true;

}

// Otherwise, forward the packet to the cluster head or base station

uint32_t myNodeId = m_ipv4->GetObject<Node>()->GetId();

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

if (std::find(m_clusterHeads.begin(),m_clusterHeads.end(), myNodeId) != m_clusterHeads.end()) {

// I am a cluster head, forward to base station

route->SetDestination(header.GetDestination());

route->SetGateway(Ipv4Address(“10.1.1.1”)); // Base station address

route->SetOutputDevice(m_ipv4->GetNetDevice(1));

} else {

// I am a member node, forward to cluster head

uint32_t clusterHead = m_nodeClusterMap[myNodeId];

route->SetDestination(header.GetDestination());

route->SetGateway(m_ipv4->GetAddress(1, 0).GetLocal());

route->SetOutputDevice(m_ipv4->GetNetDevice(1));

}

ucb(route, p, header);

return true;

}

void LeachRouting::NotifyInterfaceUp(uint32_t interface) {

NS_LOG_FUNCTION(this << interface);

}

void LeachRouting::NotifyInterfaceDown(uint32_t interface) {

NS_LOG_FUNCTION(this << interface);

}

void LeachRouting::NotifyAddAddress(uint32_t interface,

Ipv4InterfaceAddress address) {

NS_LOG_FUNCTION(this << interface << address);

}

void LeachRouting::NotifyRemoveAddress(uint32_t interface,

Ipv4InterfaceAddress address) {

NS_LOG_FUNCTION(this << interface << address);

}

}

  1. Integrate the Custom Routing Protocol:

#include “leach-routing.h”

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

CommandLine cmd;

cmd.Parse(argc, argv);

NodeContainer nodes;

nodes.Create(10);

MobilityHelper mobility;

mobility.SetPositionAllocator(“ns3::GridPositionAllocator”,

“MinX”, DoubleValue(0.0),

“MinY”, DoubleValue(0.0),

“DeltaX”, DoubleValue(10.0),

“DeltaY”, DoubleValue(10.0),

“GridWidth”, UintegerValue(5),

“LayoutType”, StringValue(“RowFirst”));

mobility.SetMobilityModel(“ns3::ConstantPositionMobilityModel”);

mobility.Install(nodes);

InternetStackHelper stack;

LeachRoutingHelper leachRouting;

Ipv4ListRoutingHelper list;

list.Add(leachRouting, 0);

stack.SetRoutingHelper(list);

stack.Install(nodes);

Ipv4AddressHelper address;

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

address.Assign(devices);

 

// Set up applications

uint16_t port = 9;

UdpEchoServerHelper server(port);

ApplicationContainer apps = server.Install(nodes.Get(0)); // Base station

apps.Start(Seconds(1.0));

apps.Stop(Seconds(10.0));

for (uint32_t i = 1; i < nodes.GetN(); ++i) {

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

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

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

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

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

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 10 nodes arranged in a grid position which uses the mobility models to position the nodes.
  2. LEACH Routing Protocol: A custom LEACH routing protocol class (LeachRouting) is implemented which handles the cluster head election, cluster formation, and data forwarding.
  3. Cluster Head Election: The ElectClusterHeads method elects cluster heads randomly. Each node has a 10% chance of becoming a cluster head.
  4. Cluster Formation: The FormClusters method assigns each node to the closest cluster head based on their positions.
  5. Route Input: The RouteInput method forwards packets either to the cluster head (if the node is a member) or to the base station (if the node is a cluster head).
  6. Integrate Custom Routing Protocol: The custom routing protocol is integrated into the ns3 stack using the LeachRoutingHelper.
  7. Applications: UdpEchoServer is set up at the base station, and UdpEchoClient applications are set up at all other nodes to send data to the base station.
  1. Running the Code
  1. Save the script to a file, for example, leach-routing.cc.
  2. Compile the script using the ns3 build system

./waf configure –enable-examples

./waf build

./waf –run scratch/leach-routing

The LEACH (Low-Energy Adaptive Clustering Hierarchy) routing is implemented in ns3 by creating a custom routing protocol that perform clustering and cluster head election functions. This protocol will integrate into the ns3 stack and run the simulation.

All projects on LEACH (Low-Energy Adaptive Clustering Hierarchy) in ns3 are worked by us we provide you with best outcomes.