How to create cluster based routing protocol using NS2?

Description

In the following code segment, sensor nodes transmits data to sink or base station (node 0) (TCL part). When the data arrives at routing layer, destination address of the packet is changed to the corresponding cluster head of the sensor. Thereafter, Cluster head forwards the data to base station either in single or multiple hops (C++ part).

  • TCL part :
    #Data transmission between all nodes to base station

    set now [$ns now]
    for {set i 1} {$i < $val(nn) } { incr i } {
    set udp [new Agent/UDP]
    $ns attach-agent $node_($i) $udp
    set cbr [new Application/Traffic/CBR]
    $cbr set packetSize_ 100
    $cbr set interval_ 0.1
    $cbr attach-agent $udp
    set null [new Agent/Null]
    $ns attach-agent $node_(0) $null
    $ns connect $udp $null
    $ns at [expr $now+$i*0.1] "$cbr start"
    $ns at [expr ($now+0.1)+$i*0.1] "$cbr stop"
    }

  • C++ part :

    if(received_count[index]<=member_count[index]) {
    ch_bs[index]=1;
    printf("Data received by CH %d time %f \n",index,CURRENT_TIME);
    Packet *p = Packet::alloc();
    struct hdr_cmn *ch = HDR_CMN(p);
    struct hdr_ip *ih = HDR_IP(p);
    ch->ptype() = PT_CBR;
    ch->size() = IP_HDR_LEN + 100;
    ch->iface() = -2;
    ch->error() = 0;
    ch->addr_type() = NS_AF_NONE;
    ch->prev_hop_ = index;</li>
    </ul>
    ih->saddr() = index;
    ih->dst_ = temp_original;
    ih->ttl_ = NETWORK_DIAMETER;
    printf("CH %d is forwarded data to BS time %f \n",index,CURRENT_TIME);
    }