Skip to main content

Simulate a hybrid CSMA network with 30 nodes and analyse fairness using Flow Monitor

Simulate a Hybrid CSMA Network with 30 Nodes and Analyse Fairness Using Flow Monitor


Aim:

To simulate a hybrid CSMA network consisting of 30 nodes using the NS-3 discrete-event network simulator, and to analyze network performance and bandwidth fairness utilizing FlowMonitor, NetAnim, PCAP traces, and Gnuplot.

Objectives:

  • Model a hybrid CSMA network scale with 30 nodes using CsmaHelper.
  • Configure multiple UDP traffic flows between the active nodes using OnOffHelper and PacketSinkHelper.
  • Collect flow-level performance statistics including throughput, delay, and packet loss using FlowMonitor.
  • Generate packet-level trace files via ASCII tracing and visualize network topology layout with NetAnim.
  • Capture transmission behaviour using PCAP traces for deep inspection in Wireshark.
  • Evaluate channel bandwidth sharing and fairness among active flows by computing Jain's Fairness Index.

Simulation Parameters:

  • Simulator: NS-3
  • Number of Nodes: 30 Nodes
  • Channel Type: CSMA (Carrier Sense Multiple Access)
  • Data Rate: 100 Mbps (CSMA Channel)
  • Propagation Delay: 6,560 ns
  • Traffic Type: UDP (OnOff Application)
  • Application Data Rate: 5 Mbps per source flow
  • Packet Size: 1024 bytes
  • Simulation Time: 22 seconds
  • Analysis Tool: FlowMonitor

Source Code:

/*
 * Hybrid CSMA Network Simulation with 30 Nodes
 * Includes:
 * FlowMonitor (fairness analysis)
 * TraceMetrics
 * NetAnim visualization
 * PCAP for Wireshark
 * Gnuplot output support
 */

#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/csma-module.h"
#include "ns3/internet-module.h"
#include "ns3/applications-module.h"
#include "ns3/netanim-module.h"
#include "ns3/flow-monitor-module.h"

using namespace ns3;

NS_LOG_COMPONENT_DEFINE("HybridCsma30Nodes");

int main(int argc, char *argv[])
{
    uint32_t nNodes = 30;

    CommandLine cmd;
    cmd.Parse(argc, argv);

    // Create nodes
    NodeContainer nodes;
    nodes.Create(nNodes);

    // Create CSMA helper
    CsmaHelper csma;
    csma.SetChannelAttribute("DataRate", StringValue("100Mbps"));
    csma.SetChannelAttribute("Delay", TimeValue(NanoSeconds(6560)));

    // Install devices
    NetDeviceContainer devices;
    devices = csma.Install(nodes);

    // Enable PCAP tracing (Wireshark)
    csma.EnablePcapAll("hybrid-csma");

    // Install Internet stack
    InternetStackHelper stack;
    stack.Install(nodes);

    // Assign IP addresses
    Ipv4AddressHelper address;
    address.SetBase("10.1.1.0", "255.255.255.0");

    Ipv4InterfaceContainer interfaces;
    interfaces = address.Assign(devices);

    // Create UDP traffic sources and sinks
    uint16_t port = 9;

    ApplicationContainer sinkApps;
    ApplicationContainer sourceApps;

    for (uint32_t i = 1; i < nNodes; i++)
    {
        // Install receiver
        PacketSinkHelper sink("ns3::UdpSocketFactory",
                              InetSocketAddress(Ipv4Address::GetAny(), port + i));

        sinkApps.Add(sink.Install(nodes.Get(i)));

        // Install sender
        OnOffHelper source("ns3::UdpSocketFactory",
                           InetSocketAddress(interfaces.GetAddress(i), port + i));

        source.SetAttribute("DataRate", StringValue("5Mbps"));
        source.SetAttribute("PacketSize", UintegerValue(1024));

        sourceApps.Add(source.Install(nodes.Get(0)));
    }

    sinkApps.Start(Seconds(1.0));
    sinkApps.Stop(Seconds(20.0));

    sourceApps.Start(Seconds(2.0));
    sourceApps.Stop(Seconds(20.0));

    // Enable NetAnim visualization
    AnimationInterface anim("hybrid-csma.xml");

    for (uint32_t i = 0; i < nNodes; i++)
    {
        anim.SetConstantPosition(nodes.Get(i), i * 5, 10);
    }

    // Enable FlowMonitor
    FlowMonitorHelper flowmon;
    Ptr<FlowMonitor> monitor = flowmon.InstallAll();

    Simulator::Stop(Seconds(22.0));
    AsciiTraceHelper ascii;
    csma.EnableAsciiAll(ascii.CreateFileStream("hybrid-csma.tr"));
    Simulator::Run();

    // FlowMonitor statistics
    monitor->CheckForLostPackets();

    Ptr<Ipv4FlowClassifier> classifier =
        DynamicCast<Ipv4FlowClassifier>(flowmon.GetClassifier());

    std::map<FlowId, FlowMonitor::FlowStats> stats =
        monitor->GetFlowStats();

    double totalThroughput = 0;

    std::cout << "\n========= FLOW MONITOR RESULTS =========\n";

    for (auto iter = stats.begin(); iter != stats.end(); ++iter)
    {
        Ipv4FlowClassifier::FiveTuple t =
            classifier->FindFlow(iter->first);

        double throughput =
            iter->second.rxBytes * 8.0 /
            (iter->second.timeLastRxPacket.GetSeconds() -
             iter->second.timeFirstTxPacket.GetSeconds()) /
            1024 / 1024;

        totalThroughput += throughput;

        std::cout << "Flow ID: " << iter->first << "\n";
        std::cout << "Source: " << t.sourceAddress << "\n";
        std::cout << "Destination: " << t.destinationAddress << "\n";
        std::cout << "Throughput: " << throughput << " Mbps\n";
        std::cout << "Delay: "
                  << (iter->second.delaySum.GetSeconds() /
                      iter->second.rxPackets)
                  << " s\n";

        std::cout << "Packets Lost: "
                  << iter->second.lostPackets << "\n\n";
    }

    std::cout << "Total Throughput: "
              << totalThroughput << " Mbps\n";

    // Save FlowMonitor XML (for fairness + gnuplot)
    monitor->SerializeToXmlFile("flowmon-results.xml", true, true);

    Simulator::Destroy();

    return 0;
}

Output and Visualization:

Simulation Terminal Output

Fig. 1 — Terminal Execution Output Showing FlowMonitor Flow Statistics for 30-Node Hybrid CSMA Network.

The simulation executes successfully, allocating distinct flow identifiers across the 29 active client-server pairs. FlowMonitor captures flow metrics such as throughput, aggregated delay, and dropped packets, exporting raw metrics to an XML document for further analysis.

Performance Graphs & Analysis:

NetAnim Network Topology Visualization

Fig. 2 — NetAnim Visualization of the 30-Node CSMA Bus Topology.

Throughput vs Flow ID Graph

Fig. 3 — Throughput vs Flow ID Distribution across nodes.

Delay vs Flow ID Graph

Fig. 4 — End-to-End Delay vs Flow ID.

Packet Loss vs Flow ID Graph

Fig. 5 — Packet Loss Distribution per Flow ID.

Throughput Fairness and Jain's Index Graph

Fig. 6 — Bandwidth Fairness Analysis and Flow Share Distribution.

Wireshark PCAP Capture Analysis:

PCAP trace files generated by the CSMA helper enable deep packet inspection via Wireshark. The captures demonstrate carrier-sense multiple access medium contention, collisions, and backoff states among the 30 nodes sharing the 100 Mbps broadcast medium.

Wireshark PCAP Inspection 1

Fig. 7 — Wireshark Packet Capture Window displaying UDP stream packets over CSMA interface.

Wireshark PCAP Inspection 2

Fig. 8 — Detailed Packet Header Information captured from hybrid CSMA simulation trace.

Result:

The simulation successfully modeled a hybrid CSMA network with 30 nodes transmitting concurrent UDP streams. FlowMonitor statistics and Gnuplot charts successfully quantified the performance parameters (throughput, end-to-end delay, and packet loss ratio) across all flows.

Inference:

  • Fairness: CSMA networks distribute shared medium access fairly among active nodes when loads are balanced, yielding a high Jain's Fairness Index close to 1.0.
  • Delay & Loss: As the number of active contending nodes scales up to 30, medium contention increases, leading to higher queuing delays and occasional packet losses.
  • Monitoring Utility: FlowMonitor combined with NetAnim and Gnuplot provides an end-to-end analytical framework for evaluating multi-node topologies in NS-3.

Tools Used:

  • NS-3 Discrete-Event Network Simulator (C++)
  • FlowMonitor Module
  • NetAnim (Network Animator)
  • Gnuplot for graph generation
  • Wireshark / PCAP Traces

Comments

Popular posts from this blog

How to Create Ubuntu 24.04 Bootable USB Using Rufus [Step-by-Step Guide]

How to Create Ubuntu 24.04 Bootable USB Using Rufus [Step-by-Step Guide] Are you planning to install or try Ubuntu 24.04 LTS ? The easiest and most reliable method is to create a bootable USB drive using Rufus on a Windows system. This detailed guide will help you create a Ubuntu 24.04 USB bootloader using Rufus with easy-to-follow steps and screenshots (optional). Here is the complete video of the bootloader creation and OS installation in Windows 11. 🧰 Requirements A USB flash drive (minimum 8GB recommended) A Windows PC Ubuntu 24.04 LTS ISO file Rufus USB creation tool 🧾 Steps to Create a Ubuntu 24.04 Bootable USB Using Rufus ✅ Step 1: Download Ubuntu 24.04 ISO Visit the official Ubuntu website and download the Ubuntu 24.04 LTS ISO file . ✅ Step 2: Download and Run Rufus Head to Rufus official site and download the latest version. Open the executable file (no installation required). ✅ Step 3: Insert USB Drive Plug in your USB drive. Rufus ...

Installing ns3 in Ubuntu 22.04 | Complete Instructions

In this post, we are going to see how to install ns-3.36.1 in Ubuntu 22.04. You can follow the video for complete details Tools used in this simulation: NS3 version ns-3.36.1  OS Used: Ubuntu 22.04 LTS Installation of NS3 (ns-3.36.1) There are some changes in the ns3 installation procedure and the dependencies. So open a terminal and issue the following commands Step 1:  Prerequisites $ sudo apt update In the following packages, all the required dependencies are taken care and you can install all these packages for the complete use of ns3. $ sudo apt install g++ python3 python3-dev pkg-config sqlite3 cmake python3-setuptools git qtbase5-dev qtchooser qt5-qmake qtbase5-dev-tools gir1.2-goocanvas-2.0 python3-gi python3-gi-cairo python3-pygraphviz gir1.2-gtk-3.0 ipython3 openmpi-bin openmpi-common openmpi-doc libopenmpi-dev autoconf cvs bzr unrar gsl-bin libgsl-dev libgslcblas0 wireshark tcpdump sqlite sqlite3 libsqlite3-dev  libxml2 libxml2-dev libc6-dev libc6-dev-i386 libc...

NS2 (NS-2.35) Installation in Ubuntu 11.10

This post will help you in installing Network Simulator 2 version NS2.35 in Ubuntu 11.10 Instructions Install Ubuntu Download NS-2.35 ( http://sourceforge.net/projects/nsnam/files/allinone/ns-allinone-2.35/ns-allinone-2.35.tar.gz/download ) Unzip or untar it to any folder (recommended is /home/ loginname) using the following commands one by one sudo apt-get update sudo apt-get install build-essential autoconf automake libxmu-dev tar zxvf ns-allinone-2.35.tar.gz cd ns-allinone-2.35 ./install Once installed the PATH information will be provided to you. Copy the PATH and LD_LIBRARY_PATH Variable to .bashrc (see a dot in the beginning) Input the path information in .bashrc file like this export PATH=$PATH:<Place your paths here> export LD_LIBRARY_PATH=$LD_LIBRARY_PATH: <place the LD_LIBRARY_PATHS> here. Once done, save the file and close execute the command source .bashrc try ns or nam to see whether your installation succeeded.