Interfacing NetSim with MATLAB

NetSim now provides users the ability to interface with MATLAB in run time


Underlying Theory:
MATLAB provides API’s to start and end the MATLAB process and send data / commands to and from MATLAB. NetSim runs these functions during initialization to simultaneously start-up a MATLAB process and whenever required send data to & from MATLAB in run time. NetSim ends the MATLAB process upon completion of the simulation.

Interfacing: An interfacing file named as NetSim_MATLAB_Interface.c is used to control the MATLAB computational engine and contains the functions –

fn_netsim_matlab_init() – which starts the MATLAB Process

fn_netsim_matlab_run() – which sends data to and from MATLAB, and sends commands to be processed in MATLAB

fn_netsim_matlab_finish() – which ends the MATLAB Process

ExMATLABCall_Ver2_4web

 

Example of MATLAB call from WLAN PHY layer in NETSIM

Example Application: In this example, we replace NetSim’s default Rayleigh fading with the Nakagami fading model from MATLAB. Calls to the above functions are made at appropriate places in the NetSim code. So, for each packet, MATLAB calculates the Nakagami fading value in run time. This value returned by MATLAB is used by NetSim as the fading power instead of using the Rayleigh model. Note that instead of sending the commands directly from NetSim to MATLAB, we can also use a MATLAB .m file which will contain the commands to be executed by MATLAB.

Video: Interfacing NetSim with MATLAB is available at https://www.youtube.com/watch?v=-c9zGfwci2g

Static routing in NetSim

Static Routing

How to Setup Static Routes in RIP and OSPF

Step1 : In inter-networks, Static Routes can be set for any scenario having a minimum of 3 routers, 2 switches and 3 wired nodes. The easiest way to do this is to first run the scenario with routing protocol set as RIP/OSPF and save the Configuration file

Step 2 : Open the Configuration file with Visual studio. Expand the Router configuration and set the Static Routing information in Application Layer property of the device, by enabling the Static routing status. Then set the appropriate Static routing file name and file path.
RIP
By default:





Change to:





OSPF
By default:





Change to:





Note:
1. Update this information in any one of the router
2. A sample StaticRouting.txt file will be available inside “C:\Program Files\NetSim standard\Docs\Sample_Configuration\Internetworks”. Appropriately modify it for the scenario.
The StaticRouting.txt file contains
1. Device Id of the Router
2. List of entries to add in the routing table
DEVICE_ID:1
ip route 192.168.0.0 255.255.255.0 192.168.0.1 [1]
ip route 192.168.1.0 255.255.255.0 192.168.1.1 [1]
DEVICE_ID:2
ip route 192.168.2.0 255.255.255.0 192.168.2.1 [1]
ip route 192.168.3.0 255.255.255.0 192.168.3.1 [1]

The above format is per standard Cisco command for static routes
ip route dest_ip mask gateway_ip [distance ]

1. The ip route is the Cisco command to add the static route
2. The dest_ip is the Network address for the destination network
3. The mask is the Subnet mask for the destination network
4. The gateway_ip is the IP address of the next-hop router
5. The distance is the administrative distance for the route. The default is 1 .

Step 3 : After this, run this configuration file through CLI and static routes will be used for routing.

How to fail a node in NetSim

In this section we explain node failure using MANET-DSR as an example

Using Device Id, Identify the Device ID of the particular device.

The fn_NetSim_DSR_Run( ) is the main function to handle all the protocol functionalities

DSR_Run( )

strcpy(pszFilepath,pszIOPath);
strcat(pszFilepath,”/Output.txt”);
fp = fopen(pszFilepath,”r”);
i=0;
if(fp)
{
while(fgets(pszConfigInput,500,fp)!= NULL)
{
sscanf(pszConfigInput,”%d %d”,&NodeArray[i],&TimeArray[i]);
i+=1;
}
}

for(i=0;i<100;i++) if((pstruEventDetails->nDeviceId == NodeArray[i])&&(pstruEventDetails->dEventTime >= TimeArray[i]))
// Node failure happens after a value of time storted in an array
{ // This just returns instead of running DSR functionality when the node is failed
pstruEventDetails->nInterfaceId = 0;
return 0;
}

Note: Add the above lines of code after the variable declarations in the function
Build the .dll by clicking Build ->Build Solution. (The dll will be created inside the Visual studio project->Debug)

Running NetSim via Command Line Interface (CLI)

NetSim provides options to run simulations via the GUI or via CLI. The CLI mode is preferred for automated execution (batch processing) of simulations. This feature is available from v7 onwards. In v7, NetSim can be run via CLI for Internetworks, Advanced Wireless Networks – MANET, Wireless Sensor Networks, Personal Area Networks and Cognitive Radio Networks only. For other networks NetSim v7 can only be run via GUI

Prior to running NetSim through command line interface (CLI), users must understand the following –
Step 1: App Path
App path is the file location in the system in which the NetSim7.0 has been installed.
The app path can be found out by right clicking the NetSim Shortcut in the desktop and selecting Open file location (In Vista and Windows 7) or Find Target (In Windows XP). The app path will be something like “C:\Program Files\NetSim Standard\bin”, depending on where NetSim is installed. The path to the bin folder of NetSim is termed as the app path.
Step 2: IO Path
IO path (Input/output Path) is the path where the input and output files of an application is
written. This is similar to the temp path of windows OS. For NetSim, the iopath is
%temp%/NetSim.  The Configuration.xml file for the scenrio to be simulated should be kept here prior to running the simulation. Note that the IO path must have write permission.
Step 3: Running NetSim through command line for Simulation
To run NetSim through command line, copy the app path where NetSimCore.exe is present and paste it in the command prompt. For floating/roaming licenses, type the following in the command prompt

>NetSimCore.exe<space> -apppath<space><app path><space>-iopath<space><io path><space> -license<space>5053@<Server IP Address>

Where,
<app path> contains all files of NetSim including NetSimCore.exe
<iopath> contains Configuration.xml and Configuration.xsd file
5053 is the port number through which the system communicates with the license server i.e  the system in which the dongle is running (for floating license users)
<Server IP Address> is the IP address of the system where NetSim license server (dongle) is running.

Sample configuration.xml files are available for Internetworks and Cognitive Radio Networks in the <apppath>/Docs/Sample_Configurations folder of the NetSim install directory. Rename the sample file as “Configuration.xml” before running NetSim through CLI. Depending on your system setting, the extension (.xml) might be implicitly present and not visible. In such cases do not add the extension, as that will cause the file to be named as configuration.xml.xml.

For node-locked licenses, type the following in the command prompt

>NetSimCore.exe<space> -apppath<space><app path><space>-iopath<space><io path><space>

Once Simulation is completed successfully and the metircs files that are requested by the end user in Configuration.xml will be written in the iopath. If any of the folder names contains white space, then mention the folder path within double quotes while specifying the folder name in the command prompt.

To know more about the options that are available to run NetSim via CLI, type the following in the command prompt.
>cd <app path>
>NetSimCore.exe -h

Adding Metric Variables in NetSim

There are two ways for you to get new Metrics in NetSim.

Option 1 (Easy): To get a “derived metric” from the existing NetSim output variables, then enable the packet trace & event trace and save them as XL files. Then use the XL UI or write VB scripts to get your derived metrics.

Option 2 (Hard): To get a completely new metric code will need to added in NetSim. An example is given below where new metrics have been added for LEACH (a new modification on the original DSR and code is available in a earlier blog entry) code,

Data_Packet_Received_PL is a new variable that has been defined in 802.15.4.h

#else

_declspec(dllimport) POWER** pstruDevicePower;

//For LEACH/Data Metrics
// Array size is 101 since maximum number of sensors is 100 and 1 for sink

_declspec(dllimport) int Data_Packet_Sent_NWL[101] ;
_declspec(dllimport) int Data_Packet_Received_NWL[10] ;
_declspec(dllimport) int Data_Packet_Sent_PL[101] ;
_declspec(dllimport) int Data_Packet_Received_PL[101] ;
_declspec(dllimport) double Lifetime[101];
#endif

This is used in packetprocessing.c in the section

#ifdef _LEACH
fn_NetSim_LEACH_GetNextHop(pstruEventDetails);
if(pstruEventDetails->nDeviceId == pstruEventDetails->pPacket->nSourceId)
Data_Packet_Sent_NWL[pstruEventDetails->nDeviceId-1] += 1;
return 1;
#endif
#ifdef _LEACH

This variable after having been updated during the simulation in the section above, is finally printed in DSR.c as shown below

_declspec(dllexport) int fn_NetSim_DSR_Metrics(char* filename)
{
//This #ifdef…..#endif block defines the LEACH Metrics, which shows the packets
//sent and received by the Network Layer and the Physicaal Layer
//To enable LEACH, uncomment the line “#define _LEACH” in DSR.h
#ifdef _LEACH
FILE* fp;
int i;
fp=fopen(filename,”a+”);
fprintf(fp,”#LEACH Metrics\n”);
fprintf(fp,”DeviceID\tData Sent(Network Layer)\tData Sent(Physical Layer)\tData Received(Network Layer)\tData Received(Physical Layer)\tLifetime(sec)\n”);
for(i=0; i<NETWORK->nDeviceCount; i++)
{
fprintf(fp,”%d\t%d\t%d\t%d\t%d\t%f\n”,NETWORK->ppstruDeviceList[i]->nDeviceId,Data_Packet_Sent_NWL[NETWORK->ppstruDeviceList[i]->nDeviceId-1],Data_Packet_Sent_PL[NETWORK->ppstruDeviceList[i]->nDeviceId-1],Data_Packet_Received_NWL[NETWORK->ppstruDeviceList[i]->nDeviceId-1],Data_Packet_Received_PL[NETWORK->ppstruDeviceList[i]->nDeviceId-1],Lifetime[NETWORK->ppstruDeviceList[i]->nDeviceId-1]/1000000);
}
fclose(fp);
#endif
return fn_NetSim_DSR_Metrics_F(filename);
}

If you face difficulty debugging code, please read the section in NetSim Help “Debugging when running NetSim via CLI (Only for Internetworks, Cognitive Radio
networks, MANET, Wireless Sensor Networks and Personal Area Network)”. Also ensure you are running as Visual studio in the administrator mode

Programming a SinkHole Attack in MANET

Introduction

SinkHole attacks are one of the intrusion attacks that a MANET faces. In a SinkHole attack, the intruder node/malicious node sends fake routing information claiming that it has an optimum route to the target which causes other nodes in the Ad Hoc Network to route data packets through it. Thus, the malicious node gets access to all the traffic and is free to tamper the data as it wishes. In this example, we show how to implement a SinkHole attack on Manet running the DSR routing Protocol using Netsim by a simple modification of the DSR Protocol source code.

Code Modification

We create a file Malicious.c in which we write the following  three functions.

int fn_NetSim_DSR_MaliciousNode(NetSim_EVENTDETAILS* ); — This function returns 1 if the current Device is the Malicious node that we have set.

int fn_NetSim_DSR_MaliciousRouteAddToCache(NetSim_EVENTDETAILS* ,DSR_PRIMITIVES* ); — This function adds the route from the current node to the target in the current nodes’ route cache.

int n_NetSim_DSR_MaliciousProcessSourceRouteOption(NetSim_EVENTDETAILS * ,DSR_PRIMITIVES* ); — This function receives the data packet from the transmitting node, sends an acknowledge request and then receives the data.

In the existing file DSR.c, in the case ctrlPacket_Route_Request in Network_In_Event, we add a false route from the present node to target in the route cache of a malicious node. Thus the malicious node will send a fake route reply. In the default case of a data packet, the malicious node will receive the data packet and then it generates an acknowledge request.

Source Code 

The following files are attached:

Visit: www.tetcos.com E-Mail: sales@tetcos.com

Accessing protocol metrics when writing custom code in NetSim

Given below is a brief example of how users can access NetSim protocol / device metrics when writing custom code. This example is based on DSR protocol in NetSim v7.1

The various DSR metrics are available in the DSR.h file, under the following structures –

struct stru_DSR_DeviceVar
{
unsigned int nRREQIdentification;
struct stru_DSR_RouteCache* pstruRouteCache;
struct stru_DSR_SendBuffer* pstruSendBuffer;
struct stru_DSR_RouteRequestTable* pstruRREQTable;
enum
{
LINK_LAYER_ACK,
NETWORK_LAYER_ACK,
}AckType;
DSR_MAINT_BUFFER* pstruMaintBuffer;
struct stru_DSR_Metrics dsrMetrics;   // This structure is defined below
};

struct stru_DSR_Metrics
{
unsigned int rreqSent;
unsigned int rreqForwarded;
unsigned int rrepSent;
unsigned int rrepForwarded;
unsigned int rerrSent;
unsigned int rerrForwarded;
unsigned int routeBreak;
unsigned int packetTransmitted;
unsigned int packetOrginated;
unsigned int packetReceived;
unsigned int packetDropped;
};

These have been type def’ed for ease of use and you can add the following code in DSR.c in fn_NetSim_DSR_Run() to get packets received

// CODE TO BE ADDED

DSR_DEVICE_VAR* device1 =  DSR_DEV_VAR(1)

/* Enter the device ID whose metrics you need. The ID of present device being executed can be got by pstruEventDetails>nDeviceID */

printf(“%d”,device1->dsrMetrics.packetReceived);

/* Similarly you can access different metrics for each of the devices */

// END OF CODE

Note that

printf(“%d\n”,devVar1->dsrMetrics.rreqSent);  //  Writes to log file available in the I/O path where the configuration file is present

fprintf(stderr,”%d\n”,devVar1->dsrMetrics.rreqSent); // Writes to command prompt.

WSN LEACH Protocol — User Contributed Code

To implement LEACH in WSN, all the sensors in the network are divided into different Clusters. For this implementation, we have used 4 clusters. The clusters are fixed in the sense that its members don’t change over time.

Each cluster has a sensor which acts as a Cluster Head (CH). The sensor with the maximum remaining energy is selected as the Cluster Head. The Cluster Head changes after some fixed number of packet receptions, which in this case is taken as 4.

The member sensors in the cluster communicate only with the Cluster Head. The sensors transmit their packets directly to the Cluster Head in a single hop. The Cluster Head, in turn, forwards these packets to the Sink either directly or via other Cluster Heads. The route from the Cluster Head to the sink has been defined as static routes.

Source Files:

Netsim’s default WSN libraries only have AoDV and DSR in layer 3. To run LEACH protocol, a few changes have been made in some of the files in DSR dll and Zigbee dll, and a new file LEACH.c containing the LEACH function is added.

A new DSR.dll should be built and placed in NetSim’s bin path. For this follow instructions provided in NetSim’s help on how to write custom code. For this new DSR dll to run LEACH, copy the following files in DSR dll

  • LEACH.c
  • StaticARP.c
  • DSR.h
  • DSR.c
  • PacketProcessing.c
  • SourceRoute.c

Follow a similar procedure for Zigbee dll by including the following files:

  • 802_15_4.h
  • 802_15_4.c
  • Sensor.c
  • ChangeRadioState.c
  • AgentModel.c

Next, to enable LEACH, uncomment the line “#define _LEACH” at the beginning of the DSR.h file. Next, to enable Static ARP, uncomment the “#define _STATIC_ARP” line in the same DSR.h file. This is done to prevent loss of power / time in setting up the ARP table initially.

Now, rebuild the DSR dll and Zigbee dll using Visual Studio, and copy the updated dlls in the Bin folder of NetSim.

Implementation Logic:

For running LEACH, we have divided the network into 4 clusters. The sensor with the maximum energy is selected as the cluster head, and is updated after every 4 packet transmissions by the cluster head.

Since we are using Static ARP, the nodes do not need to send ARP control packets. Packet transmission can start immediately.

The sensors generate the first packet at a random time less than the sensing interval. After that each sensor generates a packet after every sensing interval.

Static routes have been defined between the Cluster heads as given below:

  • Cluster Head 1            Cluster Head 3            Sink
  • Cluster Head 2            Cluster Head 4            Sink
  • Cluster Head 3            Sink
  • Cluster Head 4            Sink

When a Network Out event is generated, the nodes just need to identify the next hop. The next hop is selected in the following manner:

  • First of all, it checks whether the Device ID is the same as the Source ID to determine whether the present node is the source or an intermediate node.
  • If the node itself is the source, then the next hop is the Cluster Head of that cluster.
  • If the current node is not the source, then it must be the cluster head when the packet was forwarded to it by the source or the previous cluster head. It then checks its cluster number. Then the next hop is selected according to the static routes mentioned above.

Similarly, when a Network In event is generated, the node checks whether it’s Device ID is the same as the Destination ID. If not, it generates a Network Out event which again finds the next hop as explained previously. If it is the Destination, then a Transport In event is created.

Source Codes are attached below

Zigbee — Source C Code

DSR — Source C Code

Visit: www.tetcos.com Email: sales@tetcos.com