http://nuraini.net/2007/09/16/unicast-an
Those following code are some example code for sending packet unicast and broadcast on NS2.
void protocol::unicast(Packet *p, nsaddr_t destination)
{
hdr_cmn* hdrcmn = HDR_CMN(p);
hdr_ip* iphdr = HDR_IP(p);
// set all the necessary things for the common header
hdrcmn->next_hop_ = destination;
hdrcmn->prev_hop_ = this->addr();
hdrcmn->direction() = hdr_cmn::DOWN;
// take a look its name on packet.h
hdrcmn->ptype() = PT_PROTOCOLNAME;
hdrcmn->addr_type() = NS_AF_INET;
// setting the ip header
iphdr->saddr() = this->addr();
iphdr->sport() = 254; // 1-254
iphdr->daddr() = destination;
iphdr->dport() = 254; // 1-254
iphdr->ttl() = 32;
Scheduler::instance().schedule(ll, p, 0.0);
}
void protocol::broadcast(Packet *p)
{
hdr_cmn* hdrcmn = HDR_CMN(p);
hdr_ip* iphdr = HDR_IP(p);
// set all the necessary things for the common header
hdrcmn->next_hop_ = IP_BROADCAST;
hdrcmn->prev_hop_ = this->addr();
hdrcmn->direction() = hdr_cmn::DOWN;
// setting the ip header
iphdr->saddr() = this->addr();
iphdr->sport() = 254; // 1-254
iphdr->daddr() = IP_BROADCAST;
iphdr->dport() = 254; // 1-254
iphdr->ttl() = 32;
Scheduler::instance().schedule(ll, p, 0.0);
}
The above codes can be called anywhere on sourcecode.cc (anyname.cc). For example :int protocol::command(int argc, const char*const* argv)
{
if (argc == 4) {
if (strcmp(argv[1], "sendData“) == 0)
{
Packet* newpkt = allocpkt();
//some packet configuration
this->broadcast(newpkt);
return (TCL_OK);
}
}
When the node will receive it ?We should make recv procedure.
void protocol::recv(Packet* pkt, Handler*)
{
hdr_cmn* hdrcmn = HDR_CMN(pkt); //Access the common header for the received packet:
hdr_ip* hdrip = HDR_IP(pkt); // Access the IP header for the received packet:
cout << "node " << this->addr() << "received from node " << hdrcmn->prev_hop_;
}