Design And Implementation Of Routing Protocol In Cognitive Radio Networks

Cognitive Radio (CR) is an intelligent radio technology that utilises the unused frequency spectrum in licensed bandwidth to improve the data transmission. It is designed in such a way that it allows secondary users to use channel without interfering with primary user. Although there are some routing protocols designed for NS2 but only a few have been properly implemented.
Our project mainly revolves around design and implementation of new cognitive radio routing protocol in NS2 network simulator. For this we have modified the existing AODV protocol to support the channel selection and cognitive radio environment. We are using NS2 CRAHN module for developing our protocol since it supports spectrum sensing, spectrum decision and spectrum sharing required for simulating cognitive radio protocol.
In this routing protocol AODV is used for the route creation, data transmission and other things related to maintenance of the routes between different nodes. In this we have added support for identifying the channels on which a particular node is receiving data. It is decentralized algorithm in which there is a central channel used for exchange of protocol packets while data packets are exchanged on remaining channels.
We have implemented our own channel selection policy in this routing protocol, which selects a particular channel based on how much time that particular channel is idle. In this way by choosing the channel which sits idle at most time we are here trying to increase the channel usage efficiency.

1. INTRODUCTION'''''''''''''''''''''..7
1.1. OBJECTIVE'''''''''''''''''.... 7
1.2. MOTIVATION''''''''''''''''.... 7
1.3. COGNITIVE RADIO''''''''''''''.. 7

2. NETWORK SIMULATOR'''''''''''''''''' 11
2.1. NS STRUCTURE''''''.'''''''''' 11
2.2. NS2 SIMULATION STEPS'''''''''''... 12
2.3. ADDING A NEW PROTOCOL TO NS2 ''''''.. 13

3.1. MAJOR FUNCTIONS''''''''''''''. .20
3.2. TIMERS'''''''''''''''''.''.. .21
3.3. DATA STRUCTURES USED''''''''.''.... .22

4. RESULTS'''''''''''''''''.'''''''. .25

5. CONCLUSION''''''''''''''''''''''.. .28


Fig 1: Cognitive Radio Environment 10
Fig 2: Working of NS2 simulation 12
Fig 3: Channel Used VS Time Graph 25
Fig 4: Average Throughput VS Time Graph 26
Fig 5: End-to-End Delay VS Time Graph 27

1. Introduction
1.1 Objective
The main aim of this report is to design and implement a routing protocol for cognitive radio network in NS2.

For designing a protocol for cognitive radio network we used existing AODV protocol and added support for cognitive radio to it. We also designed a channel selection policy for selecting proper channel for data transmission.

1.2 Motivation
Many papers have been published in the field of cognitive radio network but only few algorithms have been actually implemented in the NS2 network simulator. So we thought of designing and implementing a new cognitive radio routing protocol for NS2 simulator. We first designed our routing protocol, and then studied the existing protocol codes in NS2 to understand the working and use of different functions. After properly understanding the existing code we implemented our own code.

1.3 Cognitive radio
A cognitive radio is an intelligent radio that intelligently uses radio channel in order to provide best service to users. Its transceivers are designed to use the best wireless channels in their vicinity. These devices automatically detects available channels in wireless spectrum, then accordingly changes its transmission or reception parameters to allow more concurrent wireless communications in a given spectrum band at one location.

In response to the operator's commands, the cognitive engine is capable of configuring its own parameters. These parameters include waveform, protocol, operating frequency, networking and so on. This functions as an autonomous unit in the communications environment, exchanging information about the environment with the networks it accesses and other cognitive radios (CRs). A cognitive radio monitors its own performance continuously in addition to reading the radio's outputs and then uses this information to determine the RF environment, channel conditions, link performance, etc. and adjusts the radio's settings to deliver the required quality of service subject to an appropriate combination of user requirements, operational limitations, and regulatory constraints.

1.4 Functions of Cognitive radio
The main functions of cognitive radios are:
' Power Control: Power control is used for both opportunistic spectrum access and spectrum sharing Cognitive Radio system for finding the cut off level in Signal to noise ratio supporting the channel allocation. It also imposes interference power constraints for the primary user's protection. A classic work in studying power allocation scheme is to maximize the capacity of cognitive radio networks. A joint power control and spectrum sensing is proposed for capacity maximization.
' Spectrum sensing: Detecting unutilised spectrum and sharing it without harmful interference to other users is an important requirement of the cognitive radio network. Detecting primary users is the most efficient way to detect empty spectrum in frequency band. Spectrum sensing techniques can be grouped into three categories:
' Transmitter detection: Cognitive radios must have the capability to determine if a signal from a primary user transmitter is locally present in a certain spectrum or not. There are several proposed approaches for transmitter detection:
' Energy detection: Energy detection is a spectrum sensing technique that detects the presence or absence of a signal just by measuring the received signal power. This signal detection approach is pretty much easy and convenient for practical implementation purpose. To implement energy detector, however, perfect noise variance information is required. And surprisingly when there is noise uncertainty, there is an signal to noise ratio wall below which the energy detector cannot reliably detect any transmitted signal. In, a new energy based spectrum sensing algorithm with noise variance uncertainty is proposed. This algorithm does not suffer from signal to noise ratio wall and outperforms the existing signal detectors. And moreover, the relationship between the energy detector of and that of is quantified analytically.

' Cyclostationary-feature detection: This type of spectrum sensing algorithms are motivated because most of manmade communication signals such as BPSK, QPSK, AM, OFDM exhibit cyclistationary behaviour. However, the noise signals (typically white noise) do not experience this behaviour. These detectors are robust and failsafe against noise variance uncertainty. The aim of such detectors is to exploit the cyclo-stationary nature of manmade communication signals that are buried within noise. Cyclostationary detectors can be either single cycle or multi-cycle Cyclo-stationary type.
' Moment based detector: Like in the Cyclo-stationary detectors, different man made signals such as BPSK, QPSK, Maray-QAM signals also have different n^2th moment values than that of white noise. The moment based detector exploits this behaviour to check the presence or absence of the transmitted signal.
' Cooperative detection: Refers to spectrum sensing techniques where information from multiple cognitive radio users are incorporated for primary user detection.
' Interference-based detection: This technique uses the interference in the receiver signal to detect the presence/absence of primary users. If the interference in the received signal is greater than threshold value then primary user is present.
' Spectrum management: Capturing the best available spectrum to meet user communication requirements, while not creating any harmful interference to other users. Cognitive radio should decide on the best spectrum band (of all bands available) to meet quality of service requirements. Therefore spectrum management functions are required for cognitive radio. Spectrum management functions are classified as:
' Spectrum analysis
' Spectrum decision
' Spectrum Mobility: The process where a cognitive radio user exchanges its frequency of operation target to use the spectrum in a dynamic manner by allowing the radio terminals to operate in the best available frequency band with seamless communication requirements during the transition and better spectrum must be maintained
' Spectrum Sharing: Its main task is to providing a fair spectrum scheduling method. Sharing is a major challenge in open spectrum usage and corresponds to MAC problems in existing systems.

Fig 1 Cognitive Radio Environment

2. Network Simulator

Network simulator is a discrete event simulator targeted at networking based research. It provides substantial support for simulation of TCP, routing, and multicast protocols over wired and wireless networks. It is a package of tools that simulates behaviour of networks in different scenarios. Its main task are:
' To create Network Topologies
' To log events that happen under at different times
' To analyse events in order to understand the network behaviour

2.1 NS Structure

NS use two different languages in order to perform its function. The two languages that are used in NS are:
C++: It is used to implement protocols and other things such as event schedulers, event dispatcher, traffic generators etc. All the ns libraries are made using this language. This is mainly used to implement core functionalities in NS that require it to do heavy work and need a faster language.
Object Oriented Tcl (OTcl): It is used to write simulation scripts for simulating the different scenarios. It also binds the c++ objects to the objects created by user in Tcl script for simulation.

NS is an OTcl script interpreter that has a simulation event scheduler and different network libraries. So we write an Otcl script, which initiates an event scheduler in the NS. In the script we define the topologies of the network using objects and functions from the NS2 libraries.
Traffic is added to the network and told when to start and when to end. This is handled by the event scheduler, as is the termination of the simulation. The results from the interpreter can then be analysed using the trace file or graphically displayed using nam tool. All the implementations and libraries written in C++ are precompiled in order to save processing time.
Once compiled these objects become available to the OTcl interpreter via an OTcl linkage. The linkage creates a matching OTcl object and makes available to it functions and variables that are also available to the linked C++ objects. A class hierarchy in C++ (also called the compiled hierarchy), and a similar class hierarchy within the OTcl interpreter (also called the interpreted hierarchy) are also maintained between the linkages.
If we look at the structure of NS we develop and execute in Tcl using object libraries contained in OTcl. The event scheduler and most network components of the NS are developed in C++ to give us the NS simulation. The Tclcl is the Tcl/C++ interface between OTcl and C++ languages.

Fig 2: Working of NS2 simulation

2.2 NS2 Simulation Steps

The following show the main key step procedures in defining a simulation scenario in NS2:

Step 1: Simulation Design

The first step in simulating a network is to design the simulation. In this step,
The users should determine the simulation purposes, network configuration and assumptions, the performance measures, and the type of expected results.

Step 2: Configuring and Running Simulation

This step implements the design in the first step. It consists of two phases:

' Network configuration phase: In this phase network components (e.g., node, TCP and UDP) are created and configured according to the simulation design specified by user. Also, the events such as data transfer are scheduled to start at a certain time.
' Simulation Phase: This phase starts the simulation which was configured in the Network Configuration Phase. It maintains the simulation clock and executes events on basis of time. This phase usually runs until the simulation clock reaches a threshold value specified in the Network Configuration Phase or mentioned in Tcl script by user.

In most cases, it is convenient to define a simulation scenario in a Tcl scripting file and feed the file as an input argument of an NS2 invocation (e.g., executing 'ns <file>').

To allocate our code we will firstly create a new directory called crp inside our NS2 base directory. We will create five files there:
This is the header file where will be defined all necessary timers and routing agent which performs protocol's functionality.
In this file are actually implemented all timers, routing agent and Tcl hooks.
Here are declared all packets crp protocol needs to exchange among nodes in the MANET.
Header file where our own routing table is declared.
Routing table implementation are done here.

In the crp_pkt.h header file we declare structure for different packet formats and also methods for finding packet size and extracting the information related to this packet format from the Packet class object. In this we also need to define an offset that is used for reserving space for the header by packet header manager. Packet format can be added in following way:
#define HDR_CRP_PKT(p) hdr_crp_pkt::access(p)
struct hdr_crp_pkt {

//methods and variables for different field

static int offset_;
inline static int& offset() { return offset_; }
inline static hdr_crp_pkt* access(const Packet* p) {
return (hdr_crp_pkt*)p->access(offset_);

We also need to bind our packet header to Tcl interface. We will do so in crp/ with the following code.
int crp_pkt::offset_;
static class CrpHeaderClass : public PacketHeaderClass {
CrpHeaderClass() : PacketHeaderClass("PacketHeader/Crp",
sizeof(hdr_crp_pkt)) {
} class_rtProtoCrp_hdr;
Then comes programming the Routing Agent. So we inherit the TclClass in CrpClass to bind it to Tcl .
static class CrpClass : public TclClass {
CrpClass() : TclClass("Agent/Crp") {}
TclObject* create(int argc, const char*const* argv) {
assert(argc == 5);
return (new Crp((nsaddr_t)Address::instance().str2addr(argv[4])));
} class_rtProtoCrp;
When we need to send packets after some time from the occurrence of an event, it is highly relevant to use Timer class. Since we only need to reschedule the timer and send a new control packet thus we use a simple method expire().
Void Crp_PktTimer::expire(Event* e)

Routing Agent has seven blocks:
Argument PT_CRP is used while calling constructor to know about the packets received and send by this agent.

All the operations which we want to make accessible to Tcl are written in this function. Some of these are compulsory while some are optional. It can accept different number of arguements. For eg: start command is used to start packet sending timer and configure the agent for execution. To dump routing table's contents to trace file, we use print_table command.
Other useful mandatory commands like tracetarget and port-dmux are also used. If any unknown or new command is detected then it is send to base class.

Whenever a new packet is received by the agent, then recv() function is called. This function uses hdr_common (the common header for every packet) to know about the packet. To access the header, recv() uses a user-defined macro. Another function forward_data() is called in recv(). forward_data() sends the data packet forward only if it has othernode as its destination node. If the packet is of broadcast type or has the node itself as destination, then the function delivers it to uppper layers. This all is done before TTL gets expired. An Additional function drop() is used to drop the packets. drop() takes a constant and pointer as arguement. Constant tells the reason for dropping the packet while pointer points to the packet.

The content of this function varies from protocol to protocol depending on the operations performed and constraints in the desired protocol. Still some basic settings like checking for source and destination ports to be equal to some constant RT_PORT; are checked in this function.

This function is used for sending the packet to the desired destination node. First Allocpkt() function is used for allocating the packet. The next task is to initialize all the headers. The source address of the sending node, the length of the message and the sequence number is added to packet. The size of packet need not be real calculated size of packets as it is meant only for simulation purposes. Then we need to assign the next hop which packet will go to. Address type is filled at the last. We have three choices NS_AF_ILINK, NS_AF_NONE or NS_AF_INET. Since we are implementing Internet protocol so we choose NS_AF_INET. The IP header is also configured using constant IP_DEF_TTL which gives the default TTL_ value for packets. Finally, Packets being events is scheduled to be send at designated time and is thus send accordingly.

It is used to reschedule the packet sending timer by desired value.

forward_data() sends the data packet forward only if it has other node as its destination node. If the packet is of broadcast type or has the node itself as destination, then the function delivers it to upper layers. This all is done before TTL gets expired.

The Routing Table
Routing Table is a data table stored in node that tells about the possible routes to all destinations in that networks. There are two ways to implement routing table, one is by declaring a data structure and another is by defining a new class. Here we are going to create Routing Table using classes. Routing Table may contain information's like: distances or cost associated to routes, destination addresses, next hop addresses, sequence numbers etc, but for simplicity we would only use destination address and next hop address for each route entry. The data structure we use for storing Table is Hash Map. A new file crp_rtable.h is created. As routing table gets modified frequently, thus we keep its contents in trace file using print() function. A function rt_.clear() is used to flush off all entries of Table. Given the dest address we can remove its entry from the table using rm_entry() function. Using dest address and next hop addresses, we can add an entry in routing table via add_entry function. Lookup() is an important function used to get next hop for an entry with particular dest address. If there is no such route for that node, then the function returns a constant value IP_BROADCAST. Size() function is used to get the number of entries in table. Using all abovementioned functions a Routing Table can be created and used accordingly for any protocol.
We have almost finished. We have implemented a routing agent for protocol crp inside NS2. But there are some changes we need to do in order to integrate our code inside simulator.
If we remember we had to use a constant to indicate our new packet type, PT_CRP. We will define it inside file common/packet.h.
Let's find packet_t enumeration, where all packet types are listed. We will add PT_CRP to this list as we show in the next piece of code
enum packet_t {
/* ... much more packet types ... */
PT_NTYPE // This MUST be the LAST one
Just below in same file there is definition of p_info class. Inside constructor we will provide a textual name for our packet type (line 6).

p_info() {
name_[PT_TCP]= "tcp";
name_[PT_UDP]= "udp";
name_[PT_CBR]= "cbr";
/* ... much more names ... */
name_[PT_CRP]= "crp";
Let's edit trace/cmu-trace.h file. We must add our new function as in the line number 6 of the next example.

class CMUTrace : public Trace {
/* ... definitions ... */
/* ... */
void format_aodv(Packet *p, int offset);
void format_crp(Packet *p, int offset);
The next piece of code (extracted from trace/ shows different types of traces.

#include <crp/crp_pkt.h>

void CMUTrace::format_crp(Packet *p, int offset)
struct hdr_crp_pkt* ph = HDR_CRP_PKT(p);
/*your code here for trace */

In order to call this recently created function we must change the format() in trace/

CMUTrace::format(Packet* p, const char *why)
/* ... */
case PT_PING:

case PT_CRP:
format_crp(p, offset);

/* ... */
In tcl/lib/ns-packet.tcl you must locate the next code and add crp to the list (as we do in line 2).

foreach prot
# ...
add-packet-header $prot
Default values for binded attributes have to be given inside tcl/lib/ns-default.tcl. We must go to the end of the file and write something like the next code:

# ...
# Defaults defined for Crp
Agent/Crp set accessible_var_ true
Finally we have to modify tcl/lib/ns-lib.tcl. We need to add procedures for creating a node. Our interest will be centered around creating a wireless node with crp as routing protocol.
The procedure node calls to the create-wireless-node procedure. This last one, among other tasks, is intended to set the routing agent for a node. We need to hack this procedure to create an instance of our crpprotocol.

Simulator instproc create-wireless-node args {
# ...
switch -exact $routingAgent_ {
Crp {
set ragent [$self create-crp-agent $node]
# ...
# ...
Then create-crp-agent will be coded below as shown in the next example.

Simulator instproc create-crp-agent { node } {
# Create Crp routing agent
set ragent [new Agent/Crp [$node node-addr]]
$self at 0.0 "$ragent start"
$node set ragent_ $ragent
return $ragent

3. Protocol Design and Implementation

3.1 Major Functions

SendRREQ: This function is used for generating and sending the RREQ packets to all its neighbors. During RREQ packet generation we simply fill all the field of RREQ packet, ip header and common header and se destination address to IP broadcast address. After generating RREQ packet we broadcast packet to all its neighbours. In case we do not receive any RREP packet for a certain period of time then again resend RREQ for maximum of MAX_RREQ constant defined.

RecvRREQ: This function is called when a node receives a RREQ packet. After receiving RREQ packet it first checks whether it is same packet that it has generated in sendRREQ function or not. If that's case then it simply ignores it. After this it checks weather it has already processed packet with same broadcast id and ip address or not. If it has already processed the packet then ignore the packet. And then it checks weather destination mentioned in RREQ, fresh route is available or not. If fresh route is available then send RREP packet to source node in RREQ packet. When it receives RREQ packet then it also creates a reverse route for sending RREP packets later. This reverse route remains active only for brief period of time.

SendRREP: This function is used for generating and sending the RREP packets to its neighbour mentioned in reverse route created during RREQ reception. During RREP packet generation we simply fill all the field of RREP packet, ip header and common header. After generating RREP packet we send the RREP packet to the next hop mentioned in reverse route.

RecvRREP: This function is invoked when a RREP packet is received. On receiving a RREP packet, it first create a route for the destination node mentioned in the reply packet and then it checks weather this packet was destined here or not. If this packets destination address contain it's address then it simply ignores it. If this packet is to be sent to other node then look for route to destination node of RREP packet and send it there.

SendRRER: It simply creates a RRER packet by filling all its fields and then sends the packet to the all nodes affected due to failure of a route or a neighbour.

RecvRRER: This function is invoked whenever a node receives a RRER packet. On receiving a RRER packet it simply checks which routes are affected due to it and brings them down. After it again checks which nodes are affected due to bringing down of routes and generates RRER packets and propagates it to them.

Forward: This method is used for forwarding the packet to the other nodes. If it receives a data packet and it is destined here then it checks the necessary parameters and passes the packet to the above layer. If the packets are destined to other node then send it to other node either through control channel or transmission channel depending on packet type.

get_more_idle_channel: This function calculates the channel which sits idler of all the channels and return channel number.

compute_receivers_for_channels: This function is used for calculating which channel is being used by how many neighbours of a particular node.

set_receiving_channel: This methods selects a appropriate channel using channel allocation policy and allocates channel to a node and at same time update about channel usage in repository.

3.2 Timers
BroadcastTimer: This timer is used for maintaining the cached broadcast id. This timer runs periodically and checks the broadcast id cache for expired broadcast id and removes them from the broadcast id cache.

HelloTimer: This timer periodically checks for number of receivers in each channel for every node and also if any primary user is present. After calculating receivers on each channel and checking for primary user it generates a Hello message and sends to each neighbour instructing them to select appropriate channel for them.

NeighborTimer: This timer keep checking the status of neighbours weather they are active or not. After checking the status of neighbour this timer updates the neighbour list by removing the broken neighbours and sending appropriate error messages.

ChannelIdleTimer: This timer runs every 10ms and checks for idle channel. During this process it also counts how much time a particular channel was vacant or sitting idle. It keeps record for each channel how much time they were idle. All data regarding how much time a particular channel was idle is saved in an array.

RouteCacheTimer: This timer is used for maintaining the stored route. It periodically checks the routing table for any expired route. If there is an expired or invalid route then it deletes them.

LocalRouteRepairTimer: This timer is used for locally repairing a route. It is initiated whenever the local route repair timer expires. After timer has expired it checks weather the route has been repaired or not. If route is still not up then it brought down the entire route.

3.3 Data structures Used
Precursor list: This list is used for maintaining list of precursor nodes. Precursor list is a list of nodes that are using a particular route. If due to any reason this route fails then the all node in list need to be notified about this giving them instruction to find a new route.
Data fields used are <prc_address>.

Neighbours list: This data structure is used for maintaining the list of neighbours of a particular node. This list contains ip address of all the nodes that are within transmission range of each other.
Data fields used are <nb_address, nb_expire, channel>.

Route Table: This data structure has been used for maintaining the route information. This contains all the information needed for maintaining a route. It also contains neighbours list and precursor list.
Data fields are <dst, seqno, hop, nexthop, pclist, expire, flag, nblist>
In above fields flags are used for checking whether route is active or not. If route is active then flag will be UP otherwise DOWN or ROUTE_IN_REAIR.

Above data structure also contains appropriate functions for modifying these values. There are functions for inserting or deleting values from the precursor list and neighbour list, for adding a new route or deleting a route etc.

Packets headers: There is also data structure defined for the packet header for control packets. The packet headers defined are:
struct hdr_aodv {
//data fields
static int offset_; // required by PacketHeaderManager
inline static int& offset() { return offset_; }
inline static hdr_aodv* access(const Packet* p) {
return (hdr_aodv*) p->access(offset_);
struct hdr_aodv_request {
//data fields
inline int size() {
//calculates size of packet
return sz;
struct hdr_aodv_reply {
//data fields
inline int size()
struct hdr_aodv_error {
//data fields
inline int size() ;
struct hdr_aodv_hello {
//packet data fields
inline int size()

4. Result:

4.1 Graph for number of active channel vs time for Less interfered channel allocation scheme and max idle channel mode.

Fig 3: Channel Used VS Time Graph

4.2 Graph for average throughput vs time:

Fig 4: Average Throughput VS Time Graph
4.3 Graph for End to End delay vs Time:

Fig 5: End-to-End Delay VS Time Graph
5. Conclusion

Cognitive Radio Networks being intelligent radio have many future aspects. There has been a lot of work in the field of cognitive radio routing protocols but only few algorithms have been implemented in NS2 simulator. So in order to facilitate the work of researchers in understanding the working of cognitive radio network, we thought of designing and implementing a new cognitive radio routing protocol for NS2 simulator. We first designed our routing protocol, and then studied the existing protocol codes in NS2 to understand the working and use of different functions. After properly understanding the existing code we implemented our own code. Being new to NS2, we faced a lot of difficulties while implementing the routing protocol. We made modifications to AODV protocol. After simulation the results showed slight positive variations in channel usage, average throughput and end to end delay; which can be confirmed by the graphs provided.




' 'SEARCH: A routing protocol for mobile cognitive radio ad-Hoc networks' Chowdhury, K.R. Sch. of Electr. & Comput. Eng., Georgia Inst. of Technol., Atlanta, GA Di Felice, M.



' 'CRP: A Routing Protocol for Cognitive Radio Ad Hoc Networks' Kaushik R. Chowdhury, Member, IEEE, and Ian F. Akyildiz, Fellow, IEEE

' 'Routing in cognitive radio networks: Challenges and solutions'
Matteo Cesana , Francesca Cuomo, Eylem Ekici

Source: Essay UK -

About this resource

This Information Technology essay was submitted to us by a student in order to help you with your studies.

Search our content:

  • Download this page
  • Print this page
  • Search again

  • Word count:

    This page has approximately words.



    If you use part of this page in your own work, you need to provide a citation, as follows:

    Essay UK, Design And Implementation Of Routing Protocol In Cognitive Radio Networks. Available from: <> [25-05-20].

    More information:

    If you are the original author of this content and no longer wish to have it published on our website then please click on the link below to request removal: