Accessing protocol metrics when writing custom code in NetSim

Given below is a brief example of how users can access NetSim protocol / device metrics when writing custom code. This example is based on DSR protocol in NetSim v7.1

The various DSR metrics are available in the DSR.h file, under the following structures –

struct stru_DSR_DeviceVar
unsigned int nRREQIdentification;
struct stru_DSR_RouteCache* pstruRouteCache;
struct stru_DSR_SendBuffer* pstruSendBuffer;
struct stru_DSR_RouteRequestTable* pstruRREQTable;
DSR_MAINT_BUFFER* pstruMaintBuffer;
struct stru_DSR_Metrics dsrMetrics;   // This structure is defined below

struct stru_DSR_Metrics
unsigned int rreqSent;
unsigned int rreqForwarded;
unsigned int rrepSent;
unsigned int rrepForwarded;
unsigned int rerrSent;
unsigned int rerrForwarded;
unsigned int routeBreak;
unsigned int packetTransmitted;
unsigned int packetOrginated;
unsigned int packetReceived;
unsigned int packetDropped;

These have been type def’ed for ease of use and you can add the following code in DSR.c in fn_NetSim_DSR_Run() to get packets received



/* Enter the device ID whose metrics you need. The ID of present device being executed can be got by pstruEventDetails>nDeviceID */


/* Similarly you can access different metrics for each of the devices */


Note that

printf(“%d\n”,devVar1->dsrMetrics.rreqSent);  //  Writes to log file available in the I/O path where the configuration file is present

fprintf(stderr,”%d\n”,devVar1->dsrMetrics.rreqSent); // Writes to command prompt.

WSN LEACH Protocol — User Contributed Code

To implement LEACH in WSN, all the sensors in the network are divided into different Clusters. For this implementation, we have used 4 clusters. The clusters are fixed in the sense that its members don’t change over time.

Each cluster has a sensor which acts as a Cluster Head (CH). The sensor with the maximum remaining energy is selected as the Cluster Head. The Cluster Head changes after some fixed number of packet receptions, which in this case is taken as 4.

The member sensors in the cluster communicate only with the Cluster Head. The sensors transmit their packets directly to the Cluster Head in a single hop. The Cluster Head, in turn, forwards these packets to the Sink either directly or via other Cluster Heads. The route from the Cluster Head to the sink has been defined as static routes.

Source Files:

Netsim’s default WSN libraries only have AoDV and DSR in layer 3. To run LEACH protocol, a few changes have been made in some of the files in DSR dll and Zigbee dll, and a new file LEACH.c containing the LEACH function is added.

A new DSR.dll should be built and placed in NetSim’s bin path. For this follow instructions provided in NetSim’s help on how to write custom code. For this new DSR dll to run LEACH, copy the following files in DSR dll

  • LEACH.c
  • StaticARP.c
  • DSR.h
  • DSR.c
  • PacketProcessing.c
  • SourceRoute.c

Follow a similar procedure for Zigbee dll by including the following files:

  • 802_15_4.h
  • 802_15_4.c
  • Sensor.c
  • ChangeRadioState.c
  • AgentModel.c

Next, to enable LEACH, uncomment the line “#define _LEACH” at the beginning of the DSR.h file. Next, to enable Static ARP, uncomment the “#define _STATIC_ARP” line in the same DSR.h file. This is done to prevent loss of power / time in setting up the ARP table initially.

Now, rebuild the DSR dll and Zigbee dll using Visual Studio, and copy the updated dlls in the Bin folder of NetSim.

Implementation Logic:

For running LEACH, we have divided the network into 4 clusters. The sensor with the maximum energy is selected as the cluster head, and is updated after every 4 packet transmissions by the cluster head.

Since we are using Static ARP, the nodes do not need to send ARP control packets. Packet transmission can start immediately.

The sensors generate the first packet at a random time less than the sensing interval. After that each sensor generates a packet after every sensing interval.

Static routes have been defined between the Cluster heads as given below:

  • Cluster Head 1            Cluster Head 3            Sink
  • Cluster Head 2            Cluster Head 4            Sink
  • Cluster Head 3            Sink
  • Cluster Head 4            Sink

When a Network Out event is generated, the nodes just need to identify the next hop. The next hop is selected in the following manner:

  • First of all, it checks whether the Device ID is the same as the Source ID to determine whether the present node is the source or an intermediate node.
  • If the node itself is the source, then the next hop is the Cluster Head of that cluster.
  • If the current node is not the source, then it must be the cluster head when the packet was forwarded to it by the source or the previous cluster head. It then checks its cluster number. Then the next hop is selected according to the static routes mentioned above.

Similarly, when a Network In event is generated, the node checks whether it’s Device ID is the same as the Destination ID. If not, it generates a Network Out event which again finds the next hop as explained previously. If it is the Destination, then a Transport In event is created.

Source Codes are attached below

Zigbee — Source C Code

DSR — Source C Code

Visit: Email:


TETCOS Releases NetSim v7.1

TETCOS is pleased to announce the latest release of Network Simulation Software, NetSim v7.1, which comes with several exciting features including:
  • Network Emulator add-on module
    • Allows you to connect real systems running live applications to the emulator
    • Application traffic is transmitted through the simulator and real metrics are calculated
  • Packet animator
    • Animates packet flow over wired and wireless links
    • Color variation for control, data and error packets
    • Play, pause and speed controls and node movement
  • MANET – AoDV protocol per IETF RFC 3561
  • 802.11 n and 802.11 e additions to the existing W-LAN suite of 11 a, b and g
    • Phy channel models with pathloss shadowing & fading, power and BER models
    • MAC throughput of upto 600 Mbps
    • OFDM transmission type and MIMO antennas
    • Four spatial streams
  • Special NetSim code utilities are shipped along with with necessary help and config files for:
    • Low Energy Adaptive Clustering Hierarchy (LEACH) with inter and intra clustering routing for Wireless Sensor Networks
    • Node failure and reliability in MANETs
    • Spectrum Management in Cognitive Radio Networks

NetSim Simplifies Custom Code Development

Most simulation software demand considerable knowledge of the tool by the users before starting to develop code. This is a daunting task. An objective of NetSim is to make code modification and development simpler with a much shorter learning curve. Here are three simple steps on how to start customization of code.
Example: Printing “Hello world” inside NetSim’s TCP protocol.Step 1: Set up your project: Set your compiler such that your project code compiles into a Dynamic Link Library (DLL).Step 2: Copy source code: NetSim’s installation directory contains the source code for all protocols in folder ../NetSim/Simulation/src Copy paste the following files:
a. Header files related to TCP from the path ../src/simulation/include
b. Lib files related to TCP from the path ../src/simulation/lib
c. Source files related to TCP from the path ../src/Simulation/tcp
Step 3: Modify code and replace the binary: Open TCP.c and write the Hello World print statement just after the TCP init function. Then build your code and replace the existing binary of NetSim (libTCP.dll in../NetSim/Simulation/bin) with your libTCP.dll. Next, run a simulation you would see “Hello World” in command line.
Watch this video to see how to write custom code in NetSim

NetSim v7 — Batch Processing

NetSim batch processing allows users to execute of a series of simulations without manual intervention.

Consider the example, where a user wishes to create and simulate thousands of network scenarios and store and analyze the performance metrics of each simulation run. It is impossible to do this manually using the GUI. However, this can be done by writing a batch processing program which runs NetSim via CLI.

An example C program for batch processing of NetSim is available with us and existing customers of NetSim v7 can write to us for a copy. This batch program can be customized by users as desired.

Given below are important sections of the source code of this batch program.

#define apppath “C:\\Program Files (x86)\\NetSim pro7\\bin” // change to your app path
#define iopath “F:\\NetSim_Batch_Processing”                   // change to your IO Path
#define license “5053@”                             // change to where your license server is running

main ( )
{// iterate from MIN to MAX for all of the devices to create configuration files
If { /* If certain network validation conditions are not met write the name of configuration file to                           NetSim_Batch_Log.txt. This file contains all the config files that did not meet the
necessary validation conditions and were not created during the batch execution */
Else {
//Create configuration file

      } // End of creation of all config files

Create batch file RunAll.bat
// Loop over number of configuration files, call NetSim executable which will write the output files
Run the batch file RunAll.bat
} // Main end


The “Virtual” Network Stack in NetSim v7

The Network stack is an implementation of the computer networking protocol suite. NetSim v7 features a virtual implementation of the protocol stack thereby providing closer to real world modeling and analysis capability.
The stack is a five layer TCP/IP design, with modularized IN and OUT events for layered protocol implementation, and a set of clean and well organized interfaces. The network stack also features in-built config file parser, error handler, config error logger, memory manager and metrics module.
NetSim’s virtual stack interfaces with network protocols which are modeled as Finite State Machines (FSM) and the simulation kernel which is a discrete event engine accelerated by a heuristic algorithm.NetSim v7 stack features application programming interfaces at multiple points for custom code development:

  • Network stack API’s – for designing new layers and for cross layer optimization
  • Metrics API’s – for developing new statistical measures
Apart from these API’s, protocol source code is available for designing custom protocols or extending standards-based protocols.

TETCOS Releases NetSim v7

TETCOS is pleased to announce the latest release of Network Simulation Software, NetSim v7, which comes with several exciting features including:

  • Cognitive Radio per IEEE 802.22
    • MAC Layer Control plane: TDD, Super Frame, DS-MAP, US-MAP, BW Request, Quiet Period, and Normal mode operation
    • MAC Layer Cognitive plane: Spectrum manager, Spectrum sensing function, Spectrum sensing automaton, Channel Modes
    • PHY layer: OFDMA
    • Incumbent model with incumbent detection and channel switching
  • Internetworks with combined LAN, WAN and Wireless modeling
    • Phy channel models with pathloss shadowing & fading, Power models and BER models in L1
    • Ethernet Switching, WLAN (802.11 a, b and g) in L2
    • IP, Queue Scheduling in L3
    • TCP, UDP in L4
    • RIP, OSPF Routing modules with Video, Voice, FTP, DB and Custom Traffic in L5
  • NetSim Command Line Interface (CLI)
    • Use a more concise and powerful means of control
    • Run batch simulations with automated scripts
    • Model via xml based config fil

Click on the image to enlarge

Network Stack

NetSim v7 features a virtual implementation of the protocol stack thereby providing closer to real world modeling and analysis capability. The network stack features an in-built config file parser, error handler, config error logger, memory manager, metrics module and modularized in IN and OUT events for layered protocol implementation.

Click on the image to enlarge

Please contact us for more information about functionality or pricing, or to arrange a demonstration.e

Case Study: WSN Term Project at IIT-M with NetSim

Wireless Sensor Networks (WSN) is an active area of research and given below is a case study of a WSN term project done at Indian Institute of Technology (IIT) Madras using NetSim, titled “Estimation of Carrier Sense Range and its effect on IEEE 802.15.4 Sensor Networks”


  • Building probability models: The attenuation of IEEE 802.15.4 signals was to be observed and probability models for decoding range and carrier sense range were to be developed.
  • Estimating decoding range: This is the threshold below which packets sent from the transmitter are always received, and was to be estimated in terms of the probability that two devices separated by a distance are in decoding range.
Use Case
  • Developing custom code: Source C files, Sensor.c, CheckRoute.c and CCA.c of NetSim WSN library were modified. These codes were linked and debugged using NetSim’s project work environment.
  • Modeling network configurations: Custom Sensor network configurations were created using NetSim’s XML based network configuration files
  • Generating performance metrics: Packet and event traces were used for analyzing network performance metrics such as Throughput, Probability of packet discard, Average service rate and Mean Backoff duration
  • Creating dependency graphs

  • These are directed graphs representing the probability of link establishment between sensors.These graphs were generated by sampling the probability model for each link.
  • Statistically analyzing performance: Variation in network performance, from simulation, for different dependency graphs were plotted for the 10 most likely and 10 least likely DG’s
  • Establishing confidence interval: This provides the probability that a network will operate in a corresponding range. The confidence interval for operation of the 802.15.4 Wireless Sensor network with limits of performance, i.e. throughput and packet failure probability, was established.
The complete report (1.3 Mb) is available at

Simulation of 802.22 Cognitive Radio Networks with NetSim

IEEE 802.22 Wireless Regional Area Networks (WRANs) are designed to provide broadband access to data networks. The WRAN systems will use vacant channels in the VHF and UHF bands allocated to the Television Broadcasting Service in the frequency range between 54 MHz and 862 MHz while avoiding interference to the broadcast incumbents in these bands.

NetSim v7, expected to be released in April, covers simulation of 802.22 WRAN based cognitive radio networks featuring: MAC layer model containing Super frame, DS-MAP, US-MAP, BW request, Quiet period and Normal mode operation

  1. PHY layer operating through OFDMA.
  2. CR Base station with interfaces to connect with Switch or Router and CPE’s  with a Max 512 CPE’s in each BS
  3. UGS, nrtPS, rtPS and BE QoS classes
  4. Incumbent model, Incumbent detection and channel switching
  5. Connection establishment via CID consisting of a 9-bit station ID (SID) and a 3-bit flow ID (FID).
  6. The cognitive plane consisting of Spectrum Manager, Spectrum Sensing Function, Spectrum Sensing Automaton, Channel Model.

802.22 Primitives with source C Code
The following protocol functionalities are available with source C code for extending existing algorithms: Transmit_SCH, Transmit_FCH, Transmit_DS_MAP, Transmit_US_MAP, Request_BW, Access_Phy_OFDMA, Spectrum_Manager, Spectrum_Sensing_Fn, Spectrum_Sensing_Automation, apart from various Channel_models

Network metrics such as Network Throughput, Packet Delay plus CR specific metrics such as throughputs for each QoS class, incumbent detection rate, channel switching rate etc are available.
Packet Trace & Event Trace for CR simulations are also available for performance validation, statistical analysis and custom code de-bugging.


NetSim: Packet Trace and Event Trace

NetSim allows users to generate trace files which provide detailed packet & event information useful for performance validation, statistical analysis and custom code de-bugging. The two traces that can be logged in NetSim are:

1. The Event trace: This records every single event along with associated information such as time stamp, event ID, event type etc.

2. The Packet trace: This logs a set of chosen parameters for every packet as it flows through the network such as arrival times, queuing times, departure times, payload, overhead, errors, collisions etc.

How is the trace useful?

a. Learn protocol internals: Window size variation in TCP, Route Table Formation in OSPF, Medium Access in Wi-fi, etc, are examples of protocol functionalities that can be easily understood from the trace.

bLog chosen parameters: NetSim’s trace option features a checkbox based filter where users can select only those packet / event level parameters / information which they want to log.

c. Import easily into spread sheets: Tab ordering enables the trace data to be imported into spreadsheets programs such as excel with ease for statistical analysis. Further, the events / packets are printed per line and have a unique ID and time stamp. This enables users to quickly write custom scripts to parse, inspect, plot and analyze protocol parameters.

d. Debug custom protocol implementations: Users need diagnostics that can catch logical errors without having to set a lot of breakpoints or restarting the program often. A host of information is available in the trace files and in addition the event trace has two special information fields for diagnostics a) A log of the file name and line number from where the event was generated and b) Future event (s) generated while processing the current event.

How to turn on the tracing options

By default, the packet tracing option is turned off. Users can edit the config file and “enable” packet-trace, or users can turn them on using the trace button in the UI. Event-traces are “always-on” and are available with our kernel’s debug library.


NetSim – A look at the simulation config file

Sophisticated users model their simulation via a config file that is independent of the GUI. The config file contains all required information to run the simulation including the network topology, devices, links, traffic, statistics, traces etc. Given below are important features of NetSim’s config file:

Model in XML format

Unlike, traditional simulators that use a flat text file, NetSim uses XML format given its advantages.

a. Quicker Understanding: It is easier to understand what the document holds at a glance and has moreprecise declarations of content allowing for more meaningful search results

b. Better Presentation: XML enables the separation of presentation from data and is suitable as a description for complex hierarchical data as is typical in a simulation config file

c. Automatic Format Verification: MSVC allows you to switch between XML view and Data View, and helps to locate syntax error. The schema we provide along with enables statement completion feature, as well as an option to validate the XML data.

Mirror Real Networks

Various network technologies are supported including LAN, WAN, PAN, WSN, Mobile, Cellular, Wireless and Inter-network.

Devices are modeled per the 5 layer TCP / IP stack. Users can set protocol properties in each of these layers in all devices.

Traffic can be configured as applications like FTP, Database, Voice, Video etc. Further, lower level mathematical distributions are available for packet size and inter-arrival time for users to model custom apps.

And finally, the config file provides a simple interface for linking external libraries.

Log traces and analyze metrics

The config file allows you to choose end-to-end metrics you wish to analyze and traces you want to log. A range of statistics is available including throughput, utilization, delay, error, loss etc. The packet trace can be logged in .txt or .csv format and an event trace can be generated for those using our debug libraries.

TETCOS Releases NetSim v 6.2

TETCOS is pleased to announce the latest release of Network Simulation Software, NetSim ver 6.2, which comes with several new and exciting features. Given below is a quick snapshot:

All new license roaming

Increasingly, users want to take their work “on the road.” NetSim now provides built-in license roaming capability allowing users to check out a license from a server, physically disconnect from the server and continue to use the license for a period of 24 hours after which the license is automatically returned to the server when it expires on the mobile computer.

Additional platforms and java language support

v 6.2 has been tested on 32 and 64 bit Win OS: XP, Vista, 7 and beta tested on Win 8.

In addition to C & C++ with v6.2 NetSim programming exercises now support Java based user codes.

Easier coding – More API’s and simpler debug

Several API’s have been added  in the standard version. These include RIP’s Distance Vector algorithm, Periodic, Expiration and Garbage Timers and OSPF’s Hello Packets, LSA Packets, Designated Router Selection, LSDB Formation and Djikstra’s Algorithm

All codes now take install directory and windows temp folder as Command line arguments and NetSim programming exercises now allow you put break points in your code and de-bug in runtime

IIT Kharagpur Licenses NetSim

TETCOS is happy to announce the Indian Institute of Technology (IIT) Kharagpur has licensed NetSim.

IIT Kharagpur’s motivation to License NetSim

IIT Kharagpur evaluated several competitive & open source network simulators available. They focused on level of end-user friendliness, product flexibility and technical support. Flexibility was important since their students wanted to write, link and de-bug customized code for project work. Direct technical support from the developer (and not the distributor), in terms of on-site support, telephone and e-mail support, from experienced developers, was paramount to IIT Kharagpur. In both these aspects, NetSim stood out in comparison to other simulators.

Perpetual Floating License

IIT Kharagpur also wanted the perpetual floating license option available with NetSim. The floating license option offers several advantages. First, the NetSim client licenses are not tied to any one computer. Second, the license server is also not tied to any server / computer but rather tied to a USB / Parallel port dongle. And finally, any number of NetSim client installations can be carried out. Only simultaneous running of NetSim clients is checked against the number of licenses purchased.

This means there is no effort required to move the license to a new computer or even move the license server & clients to a completely new lab. The perpetual license implies that there is no expiry date on the licenses and that IIT Kharagpur can upgrade NetSim to newer releases.


It has taken Tetcos eight years to get our first IIT to license NetSim. We wanted to take a moment to thank all our customers and partners for making NetSim successful.

Today, over 250 institutions now actively use NetSim, including BITS Pilani: Hyderabad Campus, Delhi Technical University (previously DCE), NIT Rourkela, NIT Jamshedpur, NIT Suratkal, NIT Surat, NIT Bhopal, NIT Kurukshetra and NIT Durgapur.

TETCOS releases NetSim ver 6

TETCOS is happy to announce the latest release of Network Simulation Software, NetSim ver 6, which comes with several new and exciting features –

1. New Protocols: Wireless Sensor Network, Zigbee, CDMA and GSM

2. Sample Projects: Over 50 sample projects with C source code are available based on international papers. These serve as a guide for students to complete their term projects using NetSim.

3. Simulation API’s: NetSim features a set of library functions of carefully designed protocol primtives which serve as the protocol and simulation API’s. These library functions come with source code, can be called into the development environment and linked to run the protocol. Examples of library functions available in WSN include route formation, route reply, route error, slotted and unslotted CSMA, GTS, CCA, super frame formation, beacon transmission, phy layer and agent models.

4. Programming Language: NetSim’s development environment and primitive API’s are designed for users to write their codes in C. Users need not learn scripting languages, C ++, Java etc

5. Debugging Capability: A simulation can be started and then at user determined break points in the code users can perform debug using single-step, step-over, step-out and continue etc. This can be carried out at various abstraction levels, based on where the user code links, including at a per-packet level

Currently, NetSim is being actively used in over 250 institutions across the world and is featured with the book Computer Networks and Internets, V Edition, by Dr. Douglas Comer of Purdue University.