Creating a New Agent in Network Simulator 2

How to create a new agent in NS2. You can use any version of the Simulator. The following codes will make you to understand the writing of a sample agent.


  • NS2 Simulator
  • A tcl file to test the compiled agent

If any two values are supplied from the TCL file, the agent computes the Surface area of the Cylinder which is nothing but (2* PI * r * h).  The supplied values from TCL file are r and h.

How to do that.

1. Copy the (given below ) file in ~ns-allinone-2.34/ns-2.34/newfolder
2. Make an entry in the ~ns-2.34/
    Make an entry in the OBJ_CC =
            newfolder/newagent.o \
3. in the shell prompt, go to ~ns-2.34 and give the command
4. run the file agent_new.tcl (given below)
you can see the output

Here is the C++ code to be written and compiled

//Name of the file is and put it in a folder inside ~ns-2.34/newfolder/
#include <stdio.h>
#include <string.h>
#include "agent.h"
class TSPAgent : public Agent {
        int command(int argc, const char*const* argv);
        int    tsp_var1;
        double tsp_var2;
        void   TSPPrivFunc(void);

static class TSPAgentClass : public TclClass {
       TSPAgentClass() : TclClass("Agent/TSPAgentOtcl") {}
        TclObject* create(int, const char*const*) {
                return(new TSPAgent());
} class_tsp_agent;

TSPAgent::TSPAgent() : Agent(PT_UDP) {
       bind("tsp_var1_otcl", &tsp_var1);
       bind("tsp_var2_otcl", &tsp_var2);
int TSPAgent::command(int argc, const char*const* argv) {
      if(argc == 2) {
           if(strcmp(argv[1], "call-tsp-priv-func") == 0) {
     return(Agent::command(argc, argv));

void TSPAgent::TSPPrivFunc(void) {
      Tcl& tcl = Tcl::instance();
      tcl.eval("puts \"Message From TSPPrivFunc\"");
      tcl.evalf("puts \"     Area of the Cylinder is = %f\"", tsp_var1*tsp_var2*2*3.14);

TCL Code to Test the above C++ Program (Agent)

# Create MyAgent (This will give two warning messages that
set myagent [new Agent/TSPAgentOtcl]

# Set configurable parameters of MyAgent
$myagent set tsp_var1_otcl 2
$myagent set tsp_var2_otcl 6.5

# Give a command to MyAgent
$myagent call-tsp-priv-func