Ok so after completing my project i would like to share how i did it. I am still learning but yes, i did it this way.
The scenario is Wireless.
Generating nodes is simple in NS:
set nodes(0) [$ns node]
set nodes(1) [$ns node]
where nodes is an array.
Set positions of nodes:
$nodes(0) set X_ 20.0
$nodes(0) set Y_ 100.0
You can use some kind of mathematical equations to generate a topology of nodes. i.e. their positioning. Look at ns2-directory/tcl/ex/wireless-flooding.tcl.
Generate an agent for each node and attach it with the node.
set agents(0) [new Agent/MyAgent]
$nodes(0) attach-agent $agents(0) $MESSAGE_PORT
Since all of our logical working of the protocol is done in Agents, we make a cpp class of MyAgent. Also add it in the Makefile.
class MyAgent : public Agent {
// override the recv() function.
// add the command function for this class which is called whenever this class's object is asked to do some work in tcl file.
// for storing the neighbor's address as i get from PING and PING_REPLY
std::vector myNeighbors;
}
Then every agent broadcast PING message and reply with PING_REPLY message to the sender.
This can be done by sending address ns_addr_t with parameter addr_ = -1
ns_addr_t naddr;
naddr.addr_ = -1
These messages are different type of packets and are created again in cpp class like
enum Type {PING, PING_REPLY};
class HdrPing {
Type type;
// getter and setter functions and other variables like offset.
}
For writing our logic on receiving any message, which is exactly like how our distributed protocol is made, we override recv() of Agent
void MyAgent :: recv(Packet*p, Handle*h) {
switch(HdrPing::access(p)->type) {
case PING:
// send PING_REPLY back to sender and add the source of the packet p
// to my neighbor list.
// we can get it from ipHdr->saddr(), which is source address in the
// IP header of the packet.
break;
case PING_REPLY:
// add the sender of messge to my neighbor list.
break;
// other types of messages are also programmed here.
} // close switch
}
In this way, i get to know who are my neighbors.
One can add more types of messages and more functionality.