Tuesday, October 20, 2009

Networks LAB Programs

Transmission Flow Control – Stop and Wait

Concept

  • Stop and Wait is a reliable transmission flow control protocol.
  • This protocol works only in Connection Oriented (Point to Point) Transmission.
  • The transmitting (Source) node has window size of ONE.
  • After transmission of a frame the transmitting (Source) node waits for a reply (Acknowledgement) from the receiving (Destination) node.
  • If the transmitted frame reaches the receiver (Destination) without error, the receiver (Destination) transmits a Positive Acknowledgement.
  • If the transmitted frame reaches the receiver (Destination) with error, the receiver (Destination) do not transmit acknowledgement.
  • If the transmitter receives a positive acknowledgement it transmits the next frame if any. Else if its timer expires, it retransmits the same frame again.
  • If the transmitted acknowledgment reaches the Transmitter (Destination) without error, the Transmitter (Destination) transmits the next frame if any.
  • If the transmitted frame reaches the Transmitter (Destination) with error, the Transmitter (Destination) transmits the same frame.
  • This concept of the Transmitting (Source) node waiting after transmission for a reply from the receiver is known as STOP and WAIT.

Sample Program

  • The above concept is developed into a ‘C’ program and the output is shown through a graphical interface.
  • The user has to give the required inputs.
  • Selecting the ‘Sample program’ option and clicking the ‘Link’ button on the screen starts the process of linking the Sample program.

User inputs

These inputs are got through graphical interface and stored in an external file.

The program has to parse this file and get the input.

· A text file – Contains data required for transmission. The file should of TEXT (of extension .txt) format the data in the file is converted into frames of 1 byte (minimum) and 1500 bytes (maximum) and used for transmission. The file can contain maximum of 15000 (Fifteen thousand) bytes. A browse button is provided to get the required file from the system (Computer). A file path viewer is also available to cross check the path of the inputted file.

· Error Probability Rate – Contains value that determines the number of errors in the data inputted. The value differs from ‘No error’ to ‘one error in every hundred bits (10-5) transmitted.

· User path - The path of the executable (exe) is created by the user for this module. This is required when the user wants to link his program to this module. A browse button is provided to get the required file from the system (Computer). A file path viewer is also available to cross check the path of the inputted file.

Note: The User path is not stored in the external file, as it is not required by the user program to use.

Programming

Pre-Conditions

The user has to program his code such that it accepts the input from a specific TEXT (Extension ‘Txt’) file and write the output to a specific TEXT (Extension ‘Txt’) file in the specified path, which is given at the left side of the screen.

Note: Both the input and the output should be along the path where ‘NetSim Application’ is installed.

The output should be in the specified format.

This format can be viewed by clicking the ‘Methodology’ button on the screen and under title ‘Output file format’.

Input/Output File Naming Criteria:

· The User Linking Code begins with the Reading of the Inputs from the Input file.

· The results of the code mentioned as per the Algorithm must be written into the Output file.

· The Path of the input and the output file can be viewed in the Methodology screen of every coding program.

· The file paths are displayed in the text box that is in the left side of the Methodology screen.

· The complete code for file reading and writing is given in section marked “Code” below. One needs to take care that the correct paths are mentioned for writing the input.txt and output.txt file. – These path can be got by clicking on the P Button

Example: You would see a path like C:\Program Files\NetSim 2.0\input.txt Add additional “\” to make it C:\\Program Files\\NetSim 2.0\\input.txt Paste this path wherever input.txt is opened and read

Note: The naming of the input and the output file must be same as the text displayed in the methodology screen.

There are two structures defined in this program. They are,

    • ETHFRAME – This is a frame structure of the packets that has to be transmitted in the medium. This is maintained as a singly linked list.

The structure of ETHFRAME definition is as follows:

typedef struct ETHFRAME

{

int iseq; // Sequence number used for the sliding window concept

int ipack; // Packet number for the transmitting user packet

int iframe; // Frame number for the transmitting user packet

int ierrorcount; // Error count made for the frame

char szsrcaddr[20]; // Source address of the transmitting node

char szdestaddr[20]; // Destination address of the transmitting node

char szdata[1600]; // Frame value of the transmitting frame

struct ETHFRAME* nextframe; // Pointer to the next frame

} Eth_frame;

    • NODE – This is the structure of the nodes that are configured in the network. This is maintained as a singly linked list.

The structure of NODE definition is as follows:

typedef struct NODE

{

char szname [20]; // name of the node

Eth_frame* txframe; // Transmitting list to be maintained

Eth_frame* rxframe; // Receiving list to be maintained

struct NODE* nextnode; // Pointer to the next node list

} Node;

Note: To Start with variables of above described header file are initializedandcontain no value.

After the execution of create_node (in-built function), the nodelist (global variable of type Node structure) will contain two references of node structure named "Node1" and "Node2".

Functions to be used (In-built functions)

There are four ‘In-built’ functions to be used for this module.

create_node () – This function is used to create nodes and assigns necessary memory for each node.

This function creates two nodes, which are named ‘Node1’ and ‘Node2’

Work of Nodes -

‘Node1’ is the transmitting node. Node from which the inputted data is sent and this node deletes the data that are transmitted successfully.

‘Node2’ is the receiving node. Node to which the inputted data is sent, and this node also sends appropriate acknowledgement to ‘Node1’ for the data received.

Note: Only the Nodes are created by this function, but the characteristics of the node like transmitting data, forming and transmitting acknowledgement should be programmed separately.

form_packet (char*) –This function is used to form the Packet frames.

This function gets the number of characters available in the data text file and split them into frames of 1500 bytes each. This function accepts a character pointer. The character pointer points to the data text file that is transmitted between‘Node1’ and ‘Node2’.

intro_error (int, Eth_frame*) –This function introduces error in the current frame transmitting. This function accepts two input parameters, first is the Error probability rate (the second parameter read from the input file). Second is the reference of the current frame that is to be transmitted. This function returns an integer value that gives the number of errors to be introduced in the frame.

Input / Output File Format

Input File Content

This gives us the contents of the ‘Input. Txt’ from which the user has to get the values for his program

File name – This is a string that contains the path of the text file given as input whose data is transmitted.

This is PASSED as an argument to the INBUILT function form packet.

Index – This is an integer that contains numerical value corresponding to the Error Probability Rate.

Note: A ‘delimiter ">"’ separates the above two values.

Input File Parsing

o This explains how to get values through ‘C’ program from ‘Input.Txt’.

o The user has to read the inputs from the ‘Input.Txt’ from the system.

o The file content (explained in Input File Content) has to be parsed and separated into two strings.

o In order to parse the strings and separate it into sub-strings, an INBUILT "C" function named strtok (defined in the string.h header file) is used.

o The separated sub string is sent as argument to the function mentioned in Input File Content.

Example:

FILE CONTENTS à c:\test.txt>2> -

This is stored in one character pointer szstr.

This szstr is set to the length of the file content.

FOR GETTING THE FILE NAME –

1.szfilename – strtok (szstr,">")

2.iindex – strtok (NULL,">").

Output File format

This gives us the format of Output. Txt’ to which the user has to write from his program

Each line should have four values.

Each value should be separated by a delimiter‘>’.

There should be no extra white spaces or blank lines.

Example:

Value1>Value2>Value3>Value4>

Types:

There are three types of formats of writing in the output file.

The condition of writing the types is explained in the algorithm.

Type1:

Value1 – "DT",

Value 2 –Frame number,

Value 3 – Frame’s Source address,

Value 4 – Frame’s Destination address.

Type2:

Value 1 – "EV",

Value 2 – Output of the intro_error function,

Value 3 – Frame’ Source address,

Value 4 – Frame’s Destination address.

Type3:

Value 1 – "ACK",

Value 2 – "POS",

Value 3 – Acknowledgement frame’s Source Address,

Value 4 – Acknowledgement frame’s Destination Address.

Note: The above convention to write into the ‘Output.Txt’ are mandatory.

Values in Quotes"" to be written into file ‘Output.Txt’ as it is including Case.

Example

A sample file format containing three frames transmitted from node1 to node2 is as follows:

DT>1>node1>node2>

EV>0>node1>node2>

ACK>POS>node2>node1>

DT>2>node1>node2>

EV>1>node1>node2>

DT>2>node1>node2>

EV>0>node1>node2>

ACK>POS>node2>node1>

DT>3>node1>node2>

EV>0>node1>node2>

ACK>POS>node2>node1>

In the above example three frames are to be transmitted from node1 to node2.

o Frame1 is transmitted successfully hence iret=0 and Positive ACK is formed.

o Frame2 is transmitted with an error hence iret=1 and Timer at Transmitter expires and Retransmission of Frame 2 takes place.

o Frame2 is re-transmitted successfully hence iret=0 and Positive ACK is formed.

o Frame3 is transmitted successfully hence iret=0 and Positive ACK is formed.

Algorithm

NOTE – Acknowledgement loss is not considered in the network.

1. Parse the Input.txt file and store the data file path and index from the file. Store the index value to the local variable err (Error Probability value)

2. Call the in built function create_node. Create two nodes for the network.

3. Call the in built function form_packet and pass data file path, which is got by parsing the file Input.txt.

4. Repeat the loop until the transmitting list Node1 (transmitting node) becomes empty.

1. Get the first frame of the transmitting list into a local variable of type Eth_Frame. Write the contents in TYPE1 format into file Output.txt

2. Call the in built function intro_error, pass the frame got and the variable err value as parameters. The returned value is stored in a local variable iret. Write the content in TYPE2 format into file Output.txt.

3. If the value of the iret is 0 (No Error Condition),

1. Form the positive acknowledgement and place it in the transmission list of Node2.

2. To form a positive acknowledgement create a new frame of type Eth_Frame and set the data field as "POS". Then set this frame as the first frame of Node2.

3. Get the acknowledgement value from the receiving node’s transmission list.

4. Write the content in TYPE3 format in the file Output.txt.

6.3.5. Delete the first frame from the transmission list of Node1.

6.3.6. Delete the acknowledgement frame from Node2 transmission list.

Pseudo Code

The pseudo code / algorithm is given below for stop and wait flow control.

// This szfilename variable has the output file path where the user has to write his output

strcpy(szfilename,"E:\\StopandWait\\output.txt");

fp = fopen(szfilename,"w");

fclose(fp);

while nodelist->txframe != NULL

BEGIN

//Get the current transmitting frame reference

transframe = nodelist->txframe ();

//Write the Data Value into the output file

fp = fopen (szfilename,"a+");

fprintf(fp,"DT>%d>%s>%s>\n",transframe->iframe,transframe->szsrcaddr, transframe->szdestaddr);

fclose(fp);

iret =call function intro_error (errrate, transframe);

//Write the Error value into the output file.

fp = fopen (szfilename,"a+");

fprintf(fp,"EV>%d>%s>%s>\n",iret,transframe->szsrcaddr,transframe->szdestaddr);

fclose(fp);

if iret = 0

BEGIN

//Form the Ack frame according to the iret value

Call function form_ack (transframe, 1);

// Get the acknowledgement frame reference from the tranmitting list of the receiving node

Node* acknode = NULL;

Acknode =nodelist->nextnode;

ackframe = acknode->txframe;

//Write the Positive Ack value into the file.

fp = fopen (szfilename,"a+");

fprintf(fp,"ACK>POS>%s>%s>\n",ackframe->szsrcaddr,ackframe->szdestaddr);

fclose(fp);

//Acknowledgement frame is made so delete the transmitted frame from the transmitting list of the source node

Call function del_frame (transframe ->ipack, transframe ->iframe);

//User defined function call to delete the Acknowledgement frame

Call function del_ackframe ();

END

END

Code

Copy the code on to your C\C++ editor. Write your own code where you see “Write your code here”. The pseudo code / algorithm is as given above

// This program exectutes the Transmission Flow Control - Stop and Wait Protcol.

# include

# include

# include

// Acknowledgement frame constant

# define POSACKDATA "POSITIVEPOSITIVEPOSITIVEPOSITIVEPOSITIVEACKACK"

// Retransmission Request frame constant

# define NEGACKDATA "NEGATIVENEGATIVENEGATIVENEGATIVENEGATIVEACKACK"

// A general Ethernet frame structure for making the transmission

typedef struct ETHFRAME

{

int iseq;// Sequence used for the sliding window concept

int ipack;// Packet number for the transmitting user packet

int iframe;// Frame number for the transmitting user packet

int ierrorcount;// Error count to be made for the frame,Maxium retry value for the frame

char szsrcaddr[20];// source address of the transmitting node

char szdestaddr[20];// Destination address of the transmitting node

char szdata[1600];// frame value of the transmitting frame

struct ETHFRAME* nextframe;// Pointer to the next frame

}Eth_frame;

// A general Node details structure that are to be configured in the network

typedef struct NODE

{

char szname[20];// name of the node

Eth_frame* txframe;// Transmitting list to be maintained

Eth_frame* rxframe;// Receiving list to be maintained

struct NODE* nextnode;// Pointer to the next node list

}Node;

// A global variable that has the node details that are configured in the network

Node* nodelist = NULL;

unsigned long g_ulnErrorSeed1 = 12345678;

unsigned long g_ulnErrorSeed2 = 23456781;

double idata = 0.00;

int nerrvalue = 0; // Holds the Error Probability Rate.

char szstr[300]; // Variable to get file content.

char sztype[80]; // Variable to hold the Error Probability Rate Index.

char* sztemp = NULL; // Variable to store the parsed string.

char szfilename[250]; // Variable to store the file name that has to be

// splitted into frames.

FILE* fp = NULL; // A file pointer to hold the reference for a file.

// Define a FILE pointer variable

// FILE* fp = NULL;

// Define a character pointer for making the filename

// char szfilename[250];

// A two local variables

Eth_frame* transframe = NULL;

Eth_frame* ackframe = NULL;

int iret = 0;

long double g_lfnRandomNo(long double ldBER)

{

long lx = 0;

long double ldy = 0;

long double ltemp;

g_ulnErrorSeed1 = (unsigned long)((40014 * g_ulnErrorSeed1) % (unsigned long)(2147483563));

g_ulnErrorSeed2 = (unsigned long)((40692 * g_ulnErrorSeed2) % (unsigned long)(2147483399));

lx = (long)((g_ulnErrorSeed1 - g_ulnErrorSeed2) % (long)(2147483562));

if (lx != 0)

ldy = (long double)((long double)(lx) / (long double)(2147483563));

else

ldy = (long double)((long double)(2147483562) / (long double)(2147483563));

ldy = ldy * 100000000;

ltemp = (long double)(fmod(ldy, (ldBER+1)));

return ltemp;

}

int g_fnDecideError(char cBER, short int snPacketSize)

{

float fEpsilon = 0.0;

int nPacketBits = 0;

double dPacketnoerror ;

double dPEP;

long double ldRandomNumber;

long double ldBER;

float fRand;

switch (cBER)

{

case 2:

ldBER = 100;

break;

case 3:

ldBER = 1000;

break;

case 4:

ldBER = 10000;

break;

case 5:

ldBER = 100000;

break;

case 6:

ldBER = 1000000;

break;

case 7:

ldBER = 10000000;

break;

case 8:

ldBER = 100000000;

break;

case 9:

ldBER = 1000000000;

break;

case 0:

return 0;

}

fEpsilon = (float)(1/(1.0*ldBER));

nPacketBits = snPacketSize * 8;

dPacketnoerror = (double)(pow((1-fEpsilon),nPacketBits));

dPEP = (double)(1-dPacketnoerror);

ldRandomNumber = g_lfnRandomNo(ldBER);

fRand = (float) (ldRandomNumber /(1.0*ldBER));

if (fRand <= dPEP)

{

return 1;

}

else //if(fRand>dPEP)

{

return 0;

}

}

void create_node()

{

Node* tempnode=NULL;

Node* tempnode1=NULL;

//tempnode=new Node();

tempnode=(Node *)malloc(sizeof(Node));

tempnode->rxframe = NULL;

tempnode->txframe = NULL;

tempnode->nextnode = NULL;

idata = 0.00;

if(nodelist!= NULL)

{

free(nodelist);

nodelist = NULL;

}

if(nodelist == NULL)

{

strcpy(tempnode->szname ,"node1");

nodelist = tempnode ;

}

tempnode=NULL;

// tempnode=new Node();

tempnode=(Node *)malloc(sizeof(Node));

tempnode->rxframe = NULL;

tempnode->txframe = NULL;

tempnode->nextnode = NULL;

strcpy(tempnode->szname ,"node2");

tempnode1 = nodelist;

while(tempnode1 ->nextnode != NULL)

{

tempnode1 = tempnode1->nextnode ;

}

tempnode1 ->nextnode = tempnode;

}

int form_packet(char* szstr1)

{

int iwinsize = 7;

Eth_frame *parse_frame = NULL;

Eth_frame *traverseframe = NULL;

FILE* fp = NULL;

char szstr[1600];

int iloop = 0;

int icount = 0,icount1 = 1;

fp=fopen(szstr1,"r");

while(!feof(fp))

{

szstr[iloop++]=(char)fgetc(fp);

szstr[iloop]='\0';

if(iloop>1500)

{

// parse_frame=new Eth_frame();

parse_frame=(Eth_frame *)malloc(sizeof(Eth_frame));

iloop=0;

icount++;

parse_frame->ipack = 1;

parse_frame->ierrorcount = 1;

parse_frame->iframe = icount;

if(icount1 <= 7)

{

parse_frame->iseq = icount1;

icount1++;

}

else

{

icount1=1;

parse_frame ->iseq = icount1;

icount1++;

}

strcpy(parse_frame ->szsrcaddr ,"node1");

strcpy(parse_frame->szdestaddr ,"node2");

strcpy(parse_frame->szdata,szstr);

parse_frame->nextframe = NULL;

if(nodelist->txframe == NULL)

{

nodelist->txframe = parse_frame;

}

else

{

traverseframe = nodelist->txframe;

while(traverseframe ->nextframe != NULL)

{

traverseframe=traverseframe->nextframe;

}

traverseframe->nextframe = parse_frame;

}

}

else

{

}

}

fclose(fp);

if(iloop!=0)

{

//parse_frame=new Eth_frame();

parse_frame=(Eth_frame *)malloc(sizeof(Eth_frame));

icount++;

parse_frame->ipack = 1;

parse_frame->ierrorcount = 1;

parse_frame->iframe = icount;

if(icount1 <= 7)

{

parse_frame->iseq = icount1;

icount1++;

}

else

{

icount1=1;

parse_frame ->iseq = icount1;

icount1++;

}

strcpy(parse_frame ->szsrcaddr ,"node1");

strcpy(parse_frame->szdestaddr ,"node2");

strcpy(parse_frame->szdata,szstr);

parse_frame->nextframe = NULL;

if(nodelist->txframe == NULL)

{

nodelist->txframe = parse_frame;

}

else

{

traverseframe = nodelist->txframe;

while(traverseframe ->nextframe != NULL)

{

traverseframe=traverseframe->nextframe;

}

traverseframe->nextframe = parse_frame;

}

}

else

{

}

traverseframe=nodelist->txframe;

return icount;

}

int intro_error (int nErrorRate,Eth_frame* transpacket)

{

// Define a variable to get the length of the string

double dlength = 0.00;

dlength=0;

dlength+=10;// Source Address + Destination Address + Length or type of the frame

dlength+=(double)strlen(transpacket->szdata);// Length of the Data

return(g_fnDecideError(nErrorRate,(short int)dlength));

}

/*

This function is used to delete the frame from the transmitting

list of the source node

1. ipackno -- This is an integer variable that has the packet number of the

sucessful transmitted frame.

2. iframeno -- This is an integer variable that has the packet frame number

of the sucessful transmitted frame.

*/

void del_frame(int ipackno,int iframeno)

{

// Define a two variables of type Eth_frame structure(defined in the default

// header file var_header1.h).

Eth_frame *tempframe = NULL;

Eth_frame *tempframe1 = NULL;

// nodelist - Global variable defined in var_header1.h

if(nodelist->txframe == NULL)// Source node transmission list empty.

{

return;

}

else

{

tempframe1 = nodelist->txframe; // Source node reference referred in the

// local variable of type Eth_frame.

while(nodelist ->txframe != NULL)// Traverse the Source node Transmission

// list reference.

{

// Check the current reference of the transmission list packet number

// and frame number to the passed packet and frame number.

if(nodelist->txframe->ipack == ipackno && nodelist->txframe ->iframe == iframeno)

{

//Check the current reference of the transmitting list

//is the first node.

// Then it is only one node reference in the transmitting list.

if(nodelist->txframe->nextframe == NULL && nodelist->txframe == tempframe1)

//Make the Transmission list of the Transmitting node as empty

nodelist->txframe = NULL;

//Check the current reference of the transmitting list is

//the last node,

else if(nodelist->txframe->nextframe == NULL && nodelist->txframe != tempframe1)

//Make the previous node reference to the current

//node reference as empty.

tempframe ->nextframe = NULL;

//Check the current reference of the transmitting list

//is the first node.There are some more node reference in the list

else if(nodelist->txframe->nextframe != NULL && nodelist->txframe == tempframe1)

// The Transmitting node transmission list is reference is

//changed to the next frame reference.

nodelist->txframe =nodelist->txframe->nextframe ;

else

// Change the inbetween reference

tempframe ->nextframe = nodelist->txframe ->nextframe;

return;

}

else

{

}

// Store the current reference to the local variable

tempframe = nodelist->txframe;

// Traverse the transmitting node transmission list reference

//to the next node reference

nodelist->txframe = nodelist->txframe ->nextframe ;

}

}

return;

}

/*

A function to form the acknowledgement frame in the transmission

list of the receiving node.

1. trxframe -- This is a Eth_frame reference that has the reference of the

current transmitted frame in the medium.

2. itype -- This is a integer variable that has the flag value saying what

type of acknowledgement value to be formed.

1 -- Means Acknowledgement frame.

2 -- Means Retransmission request frame.

*/

void form_ack(Eth_frame* trxframe,int itype)

{

// Create a new Eth_frame reference to form the Acknowledgement frame

// in the transmission list of the receiving node

Eth_frame* ackframe=NULL;

Node* acknode=NULL;

acknode = (Node *)malloc(sizeof(Node *));

// ackframe=new Eth_frame();

ackframe=(Eth_frame *)malloc(sizeof(Eth_frame));

// Store necessary values from the reference of the passed Eth_frame

//to the newly formed new frame

ackframe->ipack = trxframe->ipack;

ackframe->iframe = trxframe->iframe;

ackframe->iseq = trxframe->iseq;

strcpy(ackframe->szsrcaddr,trxframe->szdestaddr);

strcpy(ackframe->szdestaddr,trxframe->szsrcaddr);

ackframe->nextframe = NULL;

if(itype == 1)//Positive Ack

{

// Copy the User defined variable

strcpy(ackframe->szdata,POSACKDATA);

// Store the destination node reference from the nodelist variable

//to the local Node reference variable

acknode = nodelist->nextnode;

// Store the new created ackframe reference to the transmission

//list of the receiving node

acknode->txframe = ackframe;

}

else

{

// Copy the User defined variable

strcpy(ackframe->szdata,NEGACKDATA);

// Store the destination node reference from the nodelist variable

//to the local Node reference variable

acknode = nodelist->nextnode;

// Store the new created ackframe reference to the transmission

//list of the receiving node

acknode->txframe = ackframe;

}

}

/*

A function that returns the Eth_frame reference that has

acknowledgement frame. This reference is got from the

Transmission list of receiving node.

*/

Eth_frame* ret_ackframe()

{

// Local Node reference variable.

Node* acknode = NULL;

// Get the receiving node reference from the nodelist variable.

acknode=nodelist->nextnode;

// Return the Transmission list reference

return acknode->txframe;

}

/*

This function is used to delete the acknowledgement frame

from the transmission list of the receivng node.

*/

void del_ackframe()

{

// Local Node reference variable.

Node* acknode=NULL;

// Get the receiving node reference from the nodelist variable.

acknode=nodelist->nextnode;

// Make the Transmission list of the receving node as NULL

acknode->txframe = NULL;

}

/*

A function returning the reference of the transmitting node transmission list

This function returns a reference of type Eth_frame structure

*/

Eth_frame* ret_txframe()

{

// Return the Transmission list of the transmitting node

return nodelist->txframe;

}

void fnStop_WaitReadInput()

{

/*

Open the Input file input.txt.

This has the inputs that you have made in the front end.

The input.txt file is present where NETSIM is installed.

The path of the input.txt is specified in the V.B. Steps for getting the path

1. Click the Methodology button.

2. In the left hand side of the screen there are two file paths specified

3. The first one has the filename Input.txt (The file that has user inputs)

4. The second one has the filename Output.txt

(The file in which the user has to write his outputs)

Note:

The naming of the input and the output file

must be same as the text displayed in the

Methodology screen.

Consider the Application is Installed in c:\\netsim

*/

// Open the Input file and get the string into the local variable

fp=fopen("E:\\StopandWait\\input.txt","rb");

fgets(szstr,300,fp);

fclose(fp);

// ------ Parsing Technique ----------------

// First string parsed with strtok (inbuilt function)

sztemp=strtok(szstr,">");

// First parameter has the filename that has to be transmitted from

// the source to the destination

// Parsed string reference is stored in the local variable szfilename

strcpy(szfilename,sztemp);

// Parse the remaining string to get the Error Probability Error index

// Parse string is stored in the local variable sztype

sztemp=strtok(NULL,">");

strcpy(sztype,sztemp);

}

// This has the arguement that has the Error Probability value got from the

//function callretErrorRate defined in the header file main1.h

void stopandwait(int errrate)

{

//

Write your code here

//

}

void main()

{

// This function reads the input from the file and stores it in a variable

// which the user can use for the program

// This function defenition is present in the "Function.h" header file

fnStop_WaitReadInput();

// This function defenition is present in the "Function.h" header file

create_node ();

// This function defenition is present in the "Function.h" header file

form_packet (szfilename);

// This function defenition is present in the "Function.h" header file

nerrvalue=atoi(sztype);

// This function is the core function which executes Transmission Flow Control - Stop and

// Wait Protoocl.

stopandwait(nerrvalue);

}

Distance Vector Routing

Concept

  • This is one of the routing algorithms used in a Wide Area Network for computing the shortest path among the routes.
  • The router is one of the main devices used in a wide area network. The main task of the router is routing. It forms the routing table and delivers the packets depending upon the routes in the table – either directly or via an intermediate device (perhaps another router).
  • Each router initially has information about its all neighbors (i.e., it is directly connected). After a period of time, each router exchanges its routing table among its neighbors.
  • After a certain number exchanges, all routers have the full routing information in the particular area of the network
  • Each table exchange router recomputes the shortest path between the routers.
  • The algorithm used for this routing is called distance vector routing and the protocol used for table exchange is called Routing Information Protocol (RIP).

Pre-conditions

  • Program should read the data from ‘Input.txt’ file that is available in the application path.
  • Program should write the output data to ‘Output.txt’ file that is available in the application path.

Input/Output File Naming Criteria

  • The User Linking Code begins with the Reading of the Inputs from the input file.
  • The results of the code mentioned as per the algorithm must be written into the output file.
  • The path of the input and the output file can be viewed in the Methodology screen of every coding program.
  • The file path is displayed in the text box that is on the left of the Methodology screen.
  • The complete code for file reading and writing is given in section marked “Code” below. One needs to take care that the correct paths are mentioned for writing the input.txt and output.txt file. – These path can be got by clicking on the P Button

Example: You would see a path like

C:\Program Files\NetSim 2.0\input.txt Add additional “\” to make it C:\\Program Files\\NetSim 2.0\\input.txt Paste this path wherever input.txt is opened and read

Input file format

Input.txt’ file contains some lines of data. The data format in the input file is as follows:

RouterID-1>Router Name - 1>Number of neighbor for router -1 >Neighbor ID - 1> Neighbor ID - 2>……Neighbor ID – n

RouterID - N>Router Name- N>Number of neighbor for router -N>Neighbor ID - 1> Neighbor ID - 2>……Neighbor ID - n

The data is stored in the file with a delimiter ">" in between.

Sample File data

1>Router 1>5>2>3>4>5>6

2>Router 2>1>1

3>Router 3>1>1

4>Router 4>1>1

5>Router 5>1>1

6>Router 6>1>1

Output File Format

Write the routing table of each router in each stage into the output file.

Output.txt’ file format is as follows:

Initial Stage>Source Router ID -1>Destination RouterID>CostID>Intermediate RouterID

.

Initial Stage>Source Router ID -N>Destination RouterID>CostID>Intermediate RouterID

Next Stage>Source Router ID - 1>Destination RouterID>CostID>Intermediate RouterID

.

Next Stage>Source Router ID - N>Destination RouterID>CostID>Intermediate RouterID

.

Final Stage>Source Router ID - 1>Destination RouterID>CostID>Intermediate RouterID

.

Final Stage>Source Router ID - N>Destination RouterID>CostID>Intermediate RouterID

Sample File data

0>1>2>1>0

1>1>2>1>0

1>1>3>1>0

1>2>3>2>1

Note:

Stage ‘0’ indicates the initial stage and intermediate router id ‘0’ indicates that the source router and the destination router are directly connected. Otherwise, it reaches the destination router via an intermediate router.

Algorithm

  • Read ‘Input.txt’ file which has the required data.
  • Parse the content of the file and fill up data into the appropriate field in the structure.
  • Since the RIP algorithm is used for this purpose, the cost value between each link must be same, i.e., cost ID between the direct links is 1.
  • Now, all the routers have the initial stage of information.
  • Write the initial routing stage information into the output file ‘Output.txt’. The specification of the output file format is mentioned above.
  • Repeat the following steps until there is no change in the routing table for all routers.
    1. Take the Next Router routing table and its neighbor routing table.
    2. Add the router entry that is not in your own routing table, but exists in any one of the other routing tables. If the new router entry exists in more than one neighbor, then find the minimum cost among them. The minimum cost value details are taken as a new entry: such as source router, intermediate router, destination router and cost value, etc.
    3. Update the source router routing table cost value if both the destination router and the intermediate router field value have the same value as any one of the neighbors’ routing entry.
    4. Update the source router’s routing table entry with the new advertised one if the intermediate router value in the source table is not same, but the cost value is greater than the its neighbor’s entry.
    5. Write the next stage of routing table into the file.

Repeat steps 1 to 5 for all routers.

Check whether any changes are made in any of the routers. If yes, then repeat the above steps, otherwise, quit the process.

Code

Copy the code on to your C\C++ editor. Write your own code where you see “Write your code here”. The pseudo code / algorithm is as given below

#include

#include

#include

#include

#include

#include

#define MAXROUTER 6

struct ROUTERTABLE

{

int nDestID[MAXROUTER+1]; //Destination Router ID

int nNextHop[MAXROUTER+1]; //Intermediate Router ID

int nCostID[MAXROUTER+1]; //Distance Between Source & Destination

}Table[MAXROUTER+1];

struct Router

{

int nRouterID; //Router ID

char cRouterName[10]; //Name of the router

char cNoOfNeighbour; //Number of direct connection

char cNeighbour[MAXROUTER+1]; //Storing Neighbor ID

char cUpdate; //Flag indicate whether it has all routers information

struct ROUTERTABLE stRTable[MAXROUTER+1];

}ROUTER[8];

int nStatus=0;

char *pszAppPath=NULL;

FILE *fpOutput=NULL;

int nRouter=0,nRouterTable=0;

int g_nNoOfRouters=0;

int nStage=0;

int nNeighbour=0;

int nCheck=0;

int fnAddEntry(int nIndex,int nDest,int nNextHop,int nCostID)

{

Table[nIndex].nCostID[nDest]=nCostID;

Table[nIndex].nDestID[nDest]=nDest;

Table[nIndex].nNextHop[nDest]=nNextHop;

return 1;

}

// This is function used to add any new router to the network

int fnAddRouter(char *pszStr)

{

int nStatus=0;

char *pszToken=NULL;

char *pszOrg=NULL;

int nCount=0,nIndex=0;

//First Split the string passed into a sub string

pszOrg=(char*)malloc(strlen(pszStr)+1);

strcpy(pszOrg,pszStr);

pszToken=strtok(pszOrg,">");

nIndex=atoi(pszToken);

ROUTER[nIndex-1].nRouterID=nIndex;

pszToken = strtok(NULL,">");

strcpy(ROUTER[nIndex-1].cRouterName,pszToken);

pszToken = strtok(NULL,">");

ROUTER[nIndex-1].cNoOfNeighbour=atoi(pszToken);

ROUTER[nIndex-1].cUpdate='1';

pszToken = strtok(NULL,">");

//here we store the new router information till all router present in the network added

while(pszToken!=NULL)

{

ROUTER[nIndex-1].cNeighbour[nCount++]=atoi(pszToken);

nStatus=ROUTER[nIndex-1].cNeighbour[nCount-1];

nStatus=fnAddEntry(nIndex,nStatus,0,1);

ROUTER[nIndex-1].cNeighbour[nCount]='\0';

pszToken = strtok(NULL,">");

}

g_nNoOfRouters++;

return 1;

}

// This is function to display the shortest Path while USER developing his program

void fnDisplay(int nStage)

{

for(nRouter=1;nRouter<=g_nNoOfRouters;nRouter++)

{

for(nRouterTable=1;nRouterTable<=g_nNoOfRouters;nRouterTable++)

{

if(Table[nRouter].nDestID[nRouterTable]!=0)

{

fprintf(fpOutput,"%d>%d>%d>%d>%d\n",nStage,nRouter,Table[nRouter].nDestID[nRouterTable],Table[nRouter].nCostID[nRouterTable],Table[nRouter].nNextHop[nRouterTable]);

}

}

}

return;

}

void fnReadInput()

{

FILE *fp;

char str[80]="";

int bStatus=0;

fp=fopen("C:\\Program Files\\NetSim Academic\\Input.txt","r+");

while(!feof(fp))

{

strncpy(str,"",80);

if(fgets(str,80,fp)!=NULL)

{

bStatus=fnAddRouter(str);

if (bStatus==0)

{

break;

}

}

}

fpOutput=fopen("C:\\Program Files\\NetSim Academic\\Output.txt","w+");

fnDisplay(nStage);

fclose(fp);

}

void fnDistVectAlgorithm()

{

//Write the code for this function

//pseudo code for this function is given below.

}

void main()

{

// Read the Input from the file input.txt

fnReadInput();

//Call the Distance vector algorithm to form the table

fnDistVectAlgorithm();

fclose(fpOutput);

}

Pseudocode

Function:void fnDistVectorAlgorithm()

{

do {

This is do while... loop to update the table information till it knows all the router's information present in the network.

for nRouterTable=1 to g_nNoOfRouters Select the source router

for nNeighbour=1 to g_nNoOfRouters move to all router

if Table[nRouterTable].nCostID[nNeighbour]==1 Select the neighbor router

int nDestID=1; Declare the Destination ID variable

for nDestID=1 to g_nNoOfRouters Select the routing table of neighbor router

if nDestID!=nRouterTable In that neighbor router table check Destination field if any information is there or not.

If (Table[nRouterTable].nDestID[nDestID] == 0 and Table[nNeighbour].nDestID[nDestID]!=0) This loop is to check whether the router having cost as zero and the neighbor router having non-zero value which means it is a new information to the particular router. Now store all the neighbor router table information into the corresponding router as given below

Table[nRouterTable].nDestID[nDestID] = nDestID

Table[nRouterTable].nNextHop[nDestID] = nNeighbour

Table[nRouterTable].nCostID[nDestID] = Table[nNeighbour].nCostID[nDestID]+1)

End if

Else if ((Table[nRouterTable].nNextHop[nDestID]!=nDestID or Table[nRouterTable].nCostID[nDestID]!=1 )and (Table[nNeighbour].nDestID[nDestID]!=0))This is else part of the above if loop, this loop is to check whether the information is old and it has to update.

If the above condition is satisfied ,then compare the cost.as given below

If Table[nRouterTable].nCostID[nDestID] >Table[nNeighbour].nCostID[nDestID]

If the above condition is also satisfied then, Store the updated information in the corresponding router’s routing table as given below

Table[nRouterTable].nDestID[nDestID] = nDestID

Table[nRouterTable].nNextHop[nDestID] = nNeighbour

Table[nRouterTable].nCostID[nDestID] = Table[nNeighbour].nCostID[nDestID]+1)

End if

End else

End if

End for

End if

End for

End for

Increment the stage count

Call fnDisplay(nStage) To display the router entries

}While nStage <>Till nStage reaches to 2 this do while should continue

}

Transmission Flow Control – Go Back N

Concept

This helps the user in understanding the working of a concept.

  • This is one of the reliable transmission flow control protocols.
  • GOBACKN is Connection Oriented transmission.
  • The source node transmits the frames continuously.
  • Each frame in the buffer has a sequence number starting from 1 and increasing up to the window size.
  • The source node has a window i.e. a buffer to store the frames. This buffer size is the number of frames to be transmitted continuously.
  • The size of the window depends on the protocol designer.
  • For the first frame, the receiving node forms
    • A positive acknowledgement if the frame is received without error. The iseq value is set to 1 if it is the first frame.
      • If subsequent frames are received without error (up to window size) cumulative positive acknowledgement is formed. For each of the frames received without error, the iseq value in the acknowledgement is increased by 1. For example if frame number F2, F3, F4 and F5 are received without error and the window size is 5, the iseq value in the positive acknowledgement for F5 will be 5.
        • If the subsequent frame is received with error, the cumulative acknowledgment error-free frames is transmitted. For example if frame number F1, F2 ,F3, F4 and F5 are received among which F3 is with error, then cumulative ACK of frame 2 is transmitted to Source. If in the same window two frames or more frames are received with error, the second and the subsequent error frames are neglected. Similarly even the frames received without error after the receipt of a frame with error are neglected.
    • The source node retransmits all frames of window from the first error frame.
  • If the frames are errorless in the next transmission and if the acknowledgment is error free, the window slides by the number of error-free frames being transmitted.
  • If the acknowledgment is transmitted with error, all the frames of window at source are retransmitted, and window doesn’t slide.
  • This concept of repeating the transmission from the first error frame in the window is called as GOBACKN transmission flow control protocol.

Sample Program

· The above concept is developed into a ‘C’ program and the output is shown through a graphical interface.

· The user has to give the required inputs.

· Selecting the ‘Sample program’ option and clicking the ‘Link’ button on the screen starts the process of linking the Sample program.

User inputs

These inputs are got through graphical interface and stored in an external file.

The program has to parse this file and get the input.

· A text fileContains data required for transmission.

The file should of TEXT (of extension .txt) format

The data in the file is converted into frames of 1 byte (minimum) and 1500 bytes (maximum) and used for transmission.

The file can contain maximum of 15000 (Fifteen thousand) bytes.

A browse button is provided to get the required file from the system (Computer).

A file path viewer is also available to cross check the path of the inputted file.

· Error Probability Rate – Contains value that determines the number of errors in the data inputted.

· The value differs from ‘No error’ to ‘one error in every hundred bits (10-5)’ transmitted.

· User path - The path of the executable (exe) is created by the user for this module.

· This is required when the user wants to link his program to this module.

· A browse button is provided to get the required file from the system (Computer).

· A file path viewer is also available to cross check the path of the inputted file.

· Note: The User path is not stored in the external file, as it is not required by the user program.

Programming

This helps the user to program the concept in ‘C’.

Pre-Conditions

    • The user has to program his code such that it accepts the input from a specific TEXT (Extension ‘Txt’) file and write the output to a specific TEXT (Extension ‘Txt’) file in the specified path, which is given at the left side of the screen.

o Note: Both the input and the output should be along the path where ‘NetSim Application’ is installed.

    • The output should be in the specified format.

o This format can be viewed by clicking the ‘Methodology’ button on the screen and under title ‘Output file format’.

Input/Output File Naming Criteria:

· The User Linking Code begins with the Reading of the Inputs from the Input file.

· The results of the code mentioned as per the Algorithm must be written into the Output file.

· The Path of the input and the output file can be viewed in the Methodology screen of every coding program.

· The file paths are displayed in the text box that is in the left side of the Methodology screen.

· The complete code for file reading and writing is given in section marked “Code” below. One needs to take care that the correct paths are mentioned for writing the input.txt and output.txt file. – These path can be got by clicking on the P Button

Example: You would see a path like C:\Program Files\NetSim 2.0\input.txt Add additional “\” to make it C:\\Program Files\\NetSim 2.0\\input.txt Paste this path wherever input.txt is opened and read

Note:

The naming of the input and the output file must be same as the text displayed in the Methodology screen

There are two structures defined in program. They are,

    • ETHFRAME – This is a frame structure of the packets that has to be transmitted in the medium. This is maintained as a singly linked list.

The structure of ETHFRAME definition is as follows:

typedef struct ETHFRAME

{

int iseq; // Sequence number used for the sliding window concept

int ipack; // Packet number for the transmitting user packet

int iframe; // Frame number for the transmitting user packet

int ierrorcount; // Error count made for the frame

char szsrcaddr[20]; // Source address of the transmitting node

char szdestaddr[20]; // Destination address of the transmitting node

char szdata[1600]; // Frame value of the transmitting frame

struct ETHFRAME* nextframe; // Pointer to the next frame

} Eth_frame;

    • NODE – This is the structure of the nodes that are configured in the network. This is maintained as a singly linked list.

The structure of NODE definition is as follows:

typedef struct NODE

{

char szname [20]; // name of the node

Eth_frame* txframe; // Transmitting list to be maintained

Eth_frame* rxframe; // Receiving list to be maintained

struct NODE* nextnode; // Pointer to the next node list

} Node;

Note: To start with variables of above described header file are initialized and contain no value.

After the execution of create_node (in-built function), the nodelist (global variable of type Node structure) will contain two references of node structure named "Node1" and "Node2".

Functions to be used (In-built functions)

There are four ‘In-built’ functions to be used for this module.

create_node () – This function is used to create nodes and assigns necessary memory for each node.

This function creates two nodes, which are named ‘Node1’ and ‘Node2’

Work of Nodes

‘Node1’ is the transmitting node. Node from which the inputted data is sent, and this node deletes the data that are transmitted successfully.

‘Node2’ is the receiving node. Node to which the inputted data is sent, and this node also sends acknowledgement to ‘Node1’ for the data received.

Note: Only the Nodes are created by this function, but the characteristics of the node like transmitting data, forming and transmitting acknowledgement should be programmed separately.

form_packet (char*) – This function is used to form the Packet frames.

This function gets the number of characters available in the data text file and split them into frames of 1500 bytes each.

This function accepts a character pointer. This character pointer points to the data text file that is transmitted between‘Node1’ and ‘Node2’.

intro_error (int, Eth_frame*) – This function introduces error in the current frame transmitting.

This function accepts two input parameters, first is the Error probability rate (second parameter got from input file). Second is the reference of the current frame that is to be transmitted.

This function returns an integer value that gives the number of errors to be introduced in the frame.

int slidingcount() – This function returns the frame count i.e. the number of frames that is to be transmitted in the current window.

This function returns an integer value that gives the number of frames that is to be transmitted in the current continuous transmission.

Input / Output File Format

Input File Content
 
This gives us the contents of the ‘Input. Txt’ from which the user has to get the values for his program

o File name – This is a string that contains the path of the text file given as input whose data is transmitted.

This is PASSED as an argument to the INBUILT function form packet.

o Index – This is an integer that contains numerical value corresponding to the Error Probability Rate.

Note: A ‘delimiter ">"’ separates the above two values.

Input File Parsing

o This explains how to get values through ‘C’ program from ‘Input.Txt’.

o The user has to read the inputs from the ‘Input.Txt’ from the system.

o The file content (explained in Input File Content) has to be parsed and separated into two strings.

o In order to parse the strings and separate it into sub-strings, an INBUILT "C" function named strtok (defined in the string.h header file) is used.

o The separated sub string is sent as argument to the function mentioned in Input File Content.

Example

FILE CONTENTS à c:\test.txt>2> -

This is stored in one character pointer szstr.

This szstr is set to the length of the file content.

FOR GETTING THE FILE NAME –

1.szfilename – strtok (szstr,">")

2.iindex – strtok (NULL,">").

Output File format

This gives us the format of Output. Txt’ to which the user has to write from his program

Each line should have four values.

Each value should be separated by a delimiter‘>’.

There should be no extra white spaces or blank lines.

Example:

Value1>Value2>Value3>Value4>

Types:

There are five types of formats of writing in the output file.

Each format is written in specific condition, the types are explained below.

The condition of writing the types is explained in the algorithm.

Type1:

Value1 – "CNT",

Value 2 –output of the slidingcount function

Value 3 – "FRAMES"

Value 4 – "TRANSMIT"

Type2:

Value1 – "DT",

Value 2 –Frame number,

Value 3 – Frame’s Source address,

Value 4 – Frame’s Destination address.

Type3:

Value 1 – "EV",

Value 2 – Output of the intro_error function,

Value 3 – Frame’ Source address,

Value 4 – Frame’s Destination address.

Type4:

Value 1 – "ACK",

Value 2 – "POS",

Value 3 – Acknowledgement frame’s Source Address,

Value 4 – Acknowledgement frame’s Destination Address.

Type5

Value 1 – "DEL"

Value 2 – count of frames being deleted

Value 3 – "FRAME"

Value 4 – "DELETED"

Note: The above conventions to write into the ‘Output.Txt’ are mandatory.

Values in Quotes"" to be written into file ‘Output.Txt’ as it is including Case.

Example

Each line of the file must have four parameters as described. There should be no extra white spaces or blank lines. A sample file format of "14" frames transmitted from node1 to node2 with a window size of "7" is as follows:

CNT>7>FRAMES>TRANSMIT>

DT>1>node1>node2>

EV>0>node1>node2>

DT>2>node1>node2>

EV>0>node1>node2>

DT>3>node1>node2>

EV>0>node1>node2>

DT>4>node1>node2>

EV>0>node1>node2>

DT>5>node1>node2>

EV>0>node1>node2>

DT>6>node1>node2>

EV>0>node1>node2>

DT>7>node1>node2>

EV>0>node1>node2>

ACK>POS>node2>node1>

DEL>7>FRAME>DELETED>

CNT>7>FRAMES>TRANSMIT>

DT>8>node1>node2>

EV>0>node1>node2>

DT>9>node1>node2>

EV>1>node1>node2>

DT>10>node1>node2>

EV>0>node1>node2>

DT>11>node1>node2>

EV>0>node1>node2>

DT>12>node1>node2>

EV>0>node1>node2>

DT>13>node1>node2>

EV>0>node1>node2>

DT>14>node1>node2>

EV>0>node1>node2>

ACK>POS>node2>node1>

DEL>1>FRAME>DELETED>

CNT>6>FRAMES>TRANSMIT>

DT>9>node1>node2>

EV>0>node1>node2>

DT>10>node1>node2>

EV>0>node1>node2>

DT>11>node1>node2>

EV>0>node1>node2>

DT>12>node1>node2>

EV>0>node1>node2>

DT>13>node1>node2>

EV>0>node1>node2>

DT>14>node1>node2>

EV>0>node1>node2>

ACK>POS>node2>node1>

DEL>6>FRAME>DELETED>

In the above sample file:

Frames 1 to 7 are transmitted in a single window. Since all the "7" frames are transmitted successfully, a positive ACK is transmitted from node2 to node1 after transmitting of the 7 frames. Therefore seven frames are deleted in the node1’s transmission list and the acknowledgement frame in the node2’s transmission list is also deleted.

Frames 8 to 14 are transmitted next in a single window. The 8th frame is transmitted successfully but the 9th frame generates an error while transmitting. After this frames 10 to 14 are transmitted. Since the 9th frame (2nd in the window) generated an error, A POSITIVE ACK for frame 8 (1st in the window) is transmitted from the node2 to node1. Only the 8th frame (1st in the window) is deleted from the transmission list of the node1. The window is slided by 1 frame.

Since previous window had errors, all the frames reside in the window is transmitted again (This includes the error frames and non error frames of the previous window). Since all the "6" frames are transmitted successfully, A POSITIVE ACK is transmitted from node2 to node1 after transmitting all the 6 frames of the window. So 6 frames are deleted. And window slides to next 6 frames.

Algorithm

1) NOTE – Acknowledgement loss is not considered in the network.

1. Parse the Input.txt file and store the data file path and index from the file. Store the index value to the local variable err (Error Probability value)

2. Call the in built function create_node. Create two nodes for the network.

3. Call the in built function form_packet and pass data file path, which is got by parsing the file Input.txt.

4. Repeat the loop until the transmission list of the transmitting node becomes empty. (i.e.) Transmission list of the node1 becomes empty.

1. Set the local variable prevErrFlag (Previous Error Flag) as FALSE.

2. Call the inbuilt function slidingcount and store the return value in the local variable islindex. Write the content in TYPE1 format (described below) into output file "output.txt".

3. Get the current first frame of the transmission list of the transmitting node (i.e.) Transmission list of the node1 becomes empty.

4. Repeat the loop from 1 to the islindex

1. Write the current frame details into the file in TYPE2 Format in the output file "output.txt"

2. Call the inbuilt function intro_error with the err and the current frame as parameters and store the return value in the local variable iret. Write the details into the output file "output.txt" in TYPE3 Format.

3. If the iret value is 0 (No Error Condition)

1. Check if there was error in the previous transmission, if there was no error; use the CUMULATIVE ACK LOGIC (described below) to form the positive acknowledgement. Else the acknowledgement is not formed.

4. If the iret value is not 0 (there was error in the frame)

1. Make the Previous Error Flag as TRUE

5. Get the next frame of the transmission list of the transmitting node. (i.e.) from the node1.

5. Get the acknowledgement frame from the receiving node’s transmission list.( in ackframe)

6. If reference of the acknowledgement frame is not NULL

1. Repeat the loop from 1 to "iseq" (Value of acknowlegdgement frame ‘ackframeà iseq’

2. Delete the first frame of the transmission list of the transmitting node (i.e.) from the node1

7. Write the number of deleted frames into the output file "output.txt" as TYPE5

8. Delete the acknowledgement frame from the transmission list of the receiving node (i.e.) from the node2

CUMULATIVE ACKNOWLEDGEMENT LOGIC

If the acknowledgement is positive

1. If the receiving node’s transmission list is empty.

1. Form the new positive acknowledgement of type Eth_frame. The Source Address is the destination address of the transmitting frame. The Destination Address is the source address of the transmitting frame. The value of the iseq is made as 1. Set the DATA field as "POS". Make the frame as the first frame of the transmission list of the receiving node

2. Else

1. Increment that acknowledgement frame iseq value by 1.

Pseudo code

The pseudo code / algorithm is given below for GoBackN flow control.

//Store Transmission list of the source ode to the local Eth_frame variable

.framelist = nodelist->txframe;

//Repeat the loop until transmission list becomes empty

while nodelist->txframe != NULL

BEGIN

ialreadyerror = 0;

//Returns the number of frames to be transmitted in the current window.

isliindex =call function slidingcount();

//Write the Slinding Window count into the output file.

fp = fopen(szfilename,"a+");

fprintf(fp,"CNT>%d>FRAMES>TRANSMIT>\n",isliindex);

fclose(fp);

//Get the first frame from the transmission list

transframe = call function rettxframe(-1,-1);

//Make the looping for isliindex variable

For iloop = 0 - isliindex

BEGIN

//Write the data Value into the output file.

fp = fopen(szfilename,"a+");

fprintf(fp,"DT>%d>%s>%s>\n",transframe->iframe,transframe->szsrcaddr,transframe->szdestaddr);

fclose(fp);

/* Call the function intro_error. Store the return value to the local variable iret.

The Passed arguments

1. derrValue -- This is the variable passed to the function

(got from the function call of the retErrorrate)

2. transframe -- This is Eth_frame reference that has the

Transmitting frame got from the function call ret_txframe

*/

iret = call function intro_error (derrValue,transframe);

// Write the Error value into the output file

fp = fopen(szfilename,"a+");

fprintf(fp,"EV>%d>%s>%s>\n",iret,transframe->szsrcaddr,transframe->szdestaddr);

fclose(fp);

if iret == 0 //No Error condition

BEGIN

If ialreadyerror == 0

// Cumulative acknowledgement frame formation

call function formack(transframe);

END

else //Error Condition

ialreadyerror = 1; //Make the Already Error flag value as 1.

// Call the user defined function to get the next transmission frame of the

transmitting node.

transframe =call function rettxframe(transframe-ipack,transframe->iframe);

END

//Call the user defined function to get the acknowledgement frame

ackframe=ret_ackframe ();

//Store the current transmission list reference of the transmitting node from the local

variable framelist.

nodelist->txframe = framelist;

if ackframe != NULL //There is some positive acknowledgement formed

BEGIN

//Write the Positive Ack value into the file

fp = fopen(szfilename,"a+");

fprintf(fp,"ACK>POS>%s>%s>\n",ackframe->szsrcaddr,ackframe->szdestaddr);

fclose(fp);

For iloop=0 - ackframe->iseq

// Call the function to delete the frame from the transmission list of the

transmitting node.

framelist =call function deltxframe();

//Write the Number of frames deleted from the source node into the file.

fp = fopen(szfilename,"a+");

fprintf(fp,"DEL>%d>FRAME>DELETED>\n",ackframe->iseq);

fclose(fp);

END

//Call the user defined function to delete the acknowledgement frame

//from the transmission list of the destination node.

del_ackframe ();

END

Code

Copy the code on to your C\C++ editor. Write your own code where you see “Write your code here”. The pseudo code / algorithm is as given above

# include

# include

# include

// Acknowledgement frame constant

# define POSACKDATA "POSITIVEPOSITIVEPOSITIVEPOSITIVEPOSITIVEACKACK"

// Retransmission Request frame constant

# define NEGACKDATA "NEGATIVENEGATIVENEGATIVENEGATIVENEGATIVEACKACK"

unsigned long g_ulnErrorSeed1 = 12345678;

unsigned long g_ulnErrorSeed2 = 23456781;

double idata = 0.00;

// A general Ethernet frame structure for making the transmission

typedef struct ETHFRAME

{

int iseq;// Sequence used for the sliding window concept

int ipack;// Packet number for the transmitting user packet

int iframe;// Frame number for the transmitting user packet

int ierrorcount;// Error count to be made for the frame,Maxium retry value for the frame

char szsrcaddr[20];// source address of the transmitting node

char szdestaddr[20];// Destination address of the transmitting node

char szdata[1600];// frame value of the transmitting frame

struct ETHFRAME* nextframe;// Pointer to the next frame

}Eth_frame;

// A general Node details structure that are to be configured in the network

typedef struct NODE

{

char szname[20];// name of the node

Eth_frame* txframe;// Transmitting list to be maintained

Eth_frame* rxframe;// Receiving list to be maintained

struct NODE* nextnode;// Pointer to the next node list

}Node;

// A global variable that has the node details that are configured in the network

Node* nodelist = NULL;

int nerrValue = 0; // Holds the Error Probability Rate.

char szstr[80]; // Variable to get file content.

char sztype[80]; // Variable to hold the Error Probability Rate Index.

char* sztemp = NULL; // Variable to store the parsed string .

//char szfilename[100]; // Variable to store the file name

// that has to be splitted into frames.

FILE* fp = NULL; // A file pointer to hold the reference for a file.

// Define a FILE pointer variable

// FILE* fp = NULL;

// Define a character pointer for making the filename

char szfilename[250];

//A three local variables to hold the reference of the frame of type Eth_frame

Eth_frame* framelist = NULL;

Eth_frame* transframe=NULL;

Eth_frame* ackframe=NULL;

int isliindex = 0;//To hold the Number of frames to be transmitted in a window

int iret = 0; //Variable to get the Return value of the function

//intro_error (Function in "main.h").

int iloop = 0; //looping variable.

int ialreadyerror = 0;//An Error flag value

long double g_lfnRandomNo(long double ldBER)

{

long lx = 0;

long double ldy = 0;

long double ltemp;

g_ulnErrorSeed1 = (unsigned long)((40014 * g_ulnErrorSeed1) % (unsigned long)(2147483563));

g_ulnErrorSeed2 = (unsigned long)((40692 * g_ulnErrorSeed2) % (unsigned long)(2147483399));

lx = (long)((g_ulnErrorSeed1 - g_ulnErrorSeed2) % (long)(2147483562));

if (lx != 0)

{

ldy = (long double)((long double)(lx) / (long double)(2147483563));

}

else

{

ldy = (long double)((long double)(2147483562) / (long double)(2147483563));

}

ldy = ldy * 100000000;

ltemp = (long double)(fmod(ldy, (ldBER+1)));

return ltemp;

}

int g_fnDecideError(char cBER, short int snPacketSize)

{

float fEpsilon = 0.0;

int nPacketBits = 0;

double dPacketnoerror ;

double dPEP;

long double ldRandomNumber;

long double ldBER;

float fRand;

switch (cBER)

{

case 2:

ldBER = 100;

break;

case 3:

ldBER = 1000;

break;

case 4:

ldBER = 10000;

break;

case 5:

ldBER = 100000;

break;

case 6:

ldBER = 1000000;

break;

case 7:

ldBER = 10000000;

break;

case 8:

ldBER = 100000000;

break;

case 9:

ldBER = 1000000000;

break;

case 0:

return 0;

}

fEpsilon = (float)(1/(1.0*ldBER));

nPacketBits = snPacketSize * 8;

dPacketnoerror = (double)(pow((1-fEpsilon),nPacketBits));

dPEP = (double)(1-dPacketnoerror);

ldRandomNumber = g_lfnRandomNo(ldBER);

fRand = (float) (ldRandomNumber /(1.0*ldBER));

if (fRand <= dPEP)

{

return 1;

}

else //if(fRand>dPEP)

{

return 0;

}

}

// A function to configure the network

void create_node()

{

Node* tempnode=NULL;

Node* tempnode1=NULL;

tempnode=(Node *)malloc(sizeof(Node *));;

tempnode->rxframe = NULL;

tempnode->txframe = NULL;

tempnode->nextnode = NULL;

idata = 0.00;

if(nodelist!= NULL)

{

free (nodelist);

nodelist = NULL;

}

if(nodelist == NULL)

{

strcpy(tempnode->szname ,"node1");

nodelist = tempnode ;

}

tempnode=NULL;

tempnode=(Node *)malloc(sizeof(Node *));

tempnode->rxframe = NULL;

tempnode->txframe = NULL;

tempnode->nextnode = NULL;

strcpy(tempnode->szname ,"node2");

tempnode1 = nodelist;

while(tempnode1 ->nextnode != NULL)

{

tempnode1 = tempnode1->nextnode ;

}

tempnode1 ->nextnode = tempnode;

}

int form_packet(char* szstr1)

{

int iwinsize = 7;

Eth_frame *parse_frame = NULL;

Eth_frame *traverseframe = NULL;

FILE* fp = NULL;

char szstr[1600];

int iloop = 0;

int icount = 0,icount1 = 1;

fp=fopen(szstr1,"r");

while(!feof(fp))

{

szstr[iloop++]=(char)fgetc(fp);

szstr[iloop]='\0';

if(iloop>1500)

{

parse_frame=(Eth_frame *)malloc(sizeof(Eth_frame));

iloop=0;

icount++;

parse_frame->ipack = 1;

parse_frame->ierrorcount = 1;

parse_frame->iframe = icount;

if(icount1 <= 7)

{

parse_frame->iseq = icount1;

icount1++;

}

else

{

icount1=1;

parse_frame ->iseq = icount1;

icount1++;

}

strcpy(parse_frame ->szsrcaddr ,"node1");

strcpy(parse_frame->szdestaddr ,"node2");

strcpy(parse_frame->szdata,szstr);

parse_frame->nextframe = NULL;

if(nodelist->txframe == NULL)

{

nodelist->txframe = parse_frame;

}

else

{

traverseframe = nodelist->txframe;

while(traverseframe ->nextframe != NULL)

{

traverseframe=traverseframe->nextframe;

}

traverseframe->nextframe = parse_frame;

}

}

else

{

}

}

fclose(fp);

if(iloop!=0)

{

parse_frame=(Eth_frame *)malloc(sizeof(Eth_frame));

icount++;

parse_frame->ipack = 1;

parse_frame->ierrorcount = 1;

parse_frame->iframe = icount;

if(icount1 <= 7)

{

parse_frame->iseq = icount1;

icount1++;

}

else

{

icount1=1;

parse_frame ->iseq = icount1;

icount1++;

}

strcpy(parse_frame ->szsrcaddr ,"node1");

strcpy(parse_frame->szdestaddr ,"node2");

strcpy(parse_frame->szdata,szstr);

parse_frame->nextframe = NULL;

if(nodelist->txframe == NULL)

{

nodelist->txframe = parse_frame;

}

else

{

traverseframe = nodelist->txframe;

while(traverseframe ->nextframe != NULL)

{

traverseframe=traverseframe->nextframe;

}

traverseframe->nextframe = parse_frame;

}

}

else

{

}

traverseframe=nodelist->txframe;

return icount;

}

int intro_error (int nErrorRate,Eth_frame* transpacket)

{

// Define a variable to get the length of the string

double dlength = 0.00;

dlength=0;

dlength+=10;// Source Address + Destination Address + Length or type of the frame

dlength+=(double)strlen(transpacket->szdata);// Length of the Data

return(g_fnDecideError(nErrorRate,(short int)dlength));

}

int slidingcount()

{

int iret = 0;

Eth_frame* traverseframe=NULL;

traverseframe=nodelist->txframe;

traverseframe=traverseframe->nextframe;

iret++;

while(traverseframe!=NULL)

{

if(traverseframe==NULL)

break;

else

{

iret++;

if(iret == 8)

{

iret = 7;

break;

}

}

traverseframe = traverseframe->nextframe;

}

return iret;

}

/*

A function to get the current transmitting frame frame from the source node.

1. ipackno -- This is an integer variable that has the packet number of the

transmitting frame.

2. iframeno -- This is an integer variable that has the packet frame number

of the transmitting frame.

This function returns a Eth_frame reference. This reference points to the frame

next to the frame number iframeno (passed arguement.)

*/

Eth_frame* rettxframe(int ipackno,int iframeno)

{

// A local variable reference of type Eth_frame

Eth_frame* retframe=NULL;

if(ipackno==-1 && iframeno == -1)// Check for returning the first frame.

return nodelist->txframe;

else

{

//Traverse the transmission list of the source node until it becomes empty

while(nodelist->txframe != NULL)

{

// Current reference has the packet and the frame number same as the

// value passed.

if(nodelist->txframe->ipack == ipackno && nodelist->txframe->iframe == iframeno)

{

break;// Break the loop.

}

//Move the next reference of the transmission list of the source node.

nodelist->txframe = nodelist->txframe->nextframe;

}

// Last node return NULL else return the next frame.

if(nodelist->txframe->nextframe == NULL)

return NULL;

else

return nodelist->txframe->nextframe;

}

}

/*

A function to delete the frame from the transmission list of the source node.

This functions returns a reference of type Eth_frame that has the final

reference of the transmission list of the source node.

*/

Eth_frame* deltxframe()

{

Eth_frame* traverseframe = NULL; //Variable of type Eth_frame

traverseframe=nodelist->txframe; //Source node Transmission list reference.

if(traverseframe->nextframe == NULL)//Single frame in the list.

nodelist->txframe = NULL; //Make the Transmission list of the

//source node empty.

else

//Make the Transmission list of the source node to be pointed to the

//next frame of the list.

nodelist->txframe=nodelist->txframe->nextframe;

// Return the final Transmission list of the source node.

return nodelist->txframe;

}

/*

A function to form the acknowledgement frame in the transmission list of the

destination node.This forms the acknowledgement frame for the passed reference

of the transmitting frame.

1. trxframe -- This is of type Eth_frame that holds the reference of the

current transmitting frame.

*/

void formack(Eth_frame* trxframe)

{

// ------- Local Variable Declarations --------

//Node Instance reference to hold the destination node reference.

Node* acknode=NULL;

//Eth_frame instance to create or to hold the acknowledgement frame reference.

Eth_frame* ackframe=NULL;

// Destination node reference stored in the local variable.

acknode=nodelist->nextnode;

// Check the Destination node transmission list as empty

if(acknode->txframe == NULL)

{

//Create a new Eth_frame instance to hold acknowledgement frame reference.

ackframe = (Eth_frame *)malloc(sizeof(Eth_frame));

// Store all the necessary information of the passed trxframe reference

//to the new Eth_frame reference.

ackframe->ipack = trxframe->ipack;

ackframe ->iframe = trxframe->iframe;

ackframe->iseq = 1;

strcpy(ackframe->szsrcaddr,trxframe->szdestaddr);

strcpy(ackframe->szdestaddr,trxframe->szsrcaddr);

strcpy(ackframe->szdata,POSACKDATA);//Acknowledgement frame data value

ackframe->nextframe = NULL;// Next frame as NULL.

// Append this acknowledgement frame to the transmission list of the

// destination node.

acknode->txframe = ackframe;

}

else// Destination node Transmission list not empty.

{

// Store the Transmission list of the Destination node to the local

// Eth_frame referenced variable.

ackframe=acknode->txframe;

// Store all the necessary information of the passed trxframe

// reference to the new Eth_frame reference.

ackframe->ipack = trxframe->ipack;

ackframe ->iframe = trxframe->iframe;

ackframe->iseq = ackframe ->iseq + 1;

strcpy(ackframe->szsrcaddr,trxframe->szdestaddr);

strcpy(ackframe->szdestaddr,trxframe->szsrcaddr);

strcpy(ackframe->szdata,POSACKDATA);//Acknowledgement frame data value

}

}

/*

A function to return the Acknowledgement frame of the destination node.

This function returns the reference of the Transmission list of the

destination node.

*/

Eth_frame* ret_ackframe()

{

// A local variable of type Node to hold the destination node reference.

Node* acknode = NULL;

// Store the Destination node reference to the local variable.

acknode=nodelist->nextnode;

// Return the Transmission list of the destination node.

return acknode->txframe;

}

// A function to delete the Acknowledgement frame from the Transmission list

// of the Destination node

void del_ackframe()

{

// A local variable of type Node to hold the destination node reference.

Node* acknode=NULL;

// Store the Destination node reference to the local variable.

acknode=nodelist->nextnode;

// Make the Transmission list of the Destination node as empty.

acknode->txframe = NULL;

}

void fnGoBackNReadInput()

{

/*

Open the Input file input.txt.

This has the inputs that you have made in the front end.

The input.txt file is present where NETSIM is installed.

The path of the input.txt is specified in the V.B. Steps for getting the path

1. Click the Methodology button.

2. In the left hand side of the screen there are two file paths specified

3. The first one has the filename Input.txt (The file that has user inputs)

4. The second one has the filename Output.txt

(The file in which the user has to write his outputs)

Note:

The naming of the input and the output file

must be same as the text displayed in the

Methodology screen.

Consider the Application is Installed in c:\\netsim

*/

// Open the Input file and get the string into the local variable

fp=fopen("E:\\GBN\\input.txt","rb");

fgets(szstr,80,fp);

fclose(fp);

// ------ Parsing Technique ----------------

// First string parsed with strtok (inbuilt function)

sztemp=strtok(szstr,">");

// First parameter has the filename that has to be transmitted.

// Parsed string reference is stored in the local variable szfilename

strcpy(szfilename,sztemp);

// Parse the remaining string to get the Error Probability Error index

// Parse string is stored in the local variable sztype

sztemp=strtok(NULL,">");

strcpy(sztype,sztemp);

}

void GoBackN(int derrValue)

{

//

Write your code here

//

}

void main()

{

fnGoBackNReadInput();

// Call the function defined in the default header file main.h

create_node();

// Call the function defined in the default header file main.h

form_packet(szfilename);

// Call the function defined in the default header file main.h

// The return value is stored in the local variable derrvalue

nerrValue = atoi(sztype);

// User defined code for Go Back N

// This szfilename variable has the output file path where the user has to

write his output

strcpy(szfilename,"E:\\GBN\\output.txt");

fp = fopen(szfilename,"w");

fclose(fp);

GoBackN(nerrValue);

}

Transmission Flow Control – Selective Repeat

Concept

    • This is one of the reliable transmission flow control protocols.
    • Selective Repeat is Connection Oriented transmission.
    • The source node transmits the frames continuously.
    • Each frame in the buffer has a sequence number starting from 1 and increasing up to the window size.
    • The source node has a window i.e. a buffer to store the frames. This buffer size is the number of frames to be transmitted continuously.
    • The receiver has a buffer to store the received frames. The size of the buffer depends upon the window size defined by the protocol designer.
    • The size of the window depends according to the protocol designer.
    • The source node transmits frames continuously till the window size is exhausted. If any of the frames are received with error only those frames are requested for retransmission (with a negative acknowledgement)
    • If all the frames are received without error, a cumulative positive acknowledgement is sent. I.e. ACK5 if the window size is 5 and if all the five frames are received without error.
    • If there is an error in frame 3, an acknowledgement for the frame 2 is sent and then only Frame 3 is retransmitted. For example, let window size is 5 and F1, F2, F3, F4 and F5 are being transmitted. Let F3 is transmitted with error. Then ACK2 and ACK5 are formed and ACK2 is transmitted to Source. Now Source retransmits only F3. If F3 transmits without error, then ACK5 is transmitted back to Source. Now the window slides to get the next frames to the window.
    • If acknowledgment is transmitted with error, all the frames of window are retransmitted. Else ordinary window sliding takes place. (* In implementation part, Acknowledgment error is not considered)
    • If all the frames transmitted are errorless the next transmission is carried out for the new window.
    • This concept of repeating the transmission for the error frames only is called Selective Repeat transmission flow control protocol.

Sample Program

    • The above concept is developed into a ‘C’ program and the output is shown through a graphical interface.
    • The user has to give the required inputs.
    • Selecting the ‘Sample program’ option and clicking the ‘Link’ button on the screen starts the process of linking the Sample program.

User inputs

These inputs are got through graphical interface and stored in an external file.

The program has to parse this file and get the input.

    • A text file – Contains data required for transmission. The file should of TEXT (of extension .txt) format the data in the file is converted into frames of 1 byte (minimum) and 1500 bytes (maximum) and used for transmission. The file can contain maximum of 15000 (Fifteen thousand) bytes. A browse button is provided to get the required file from the system (Computer). A file path viewer is also available to cross check the path of the inputted file.
    • Error Probability Rate – Contains value that determines the number of errors in the data inputted. The value differs from ‘No error’ to ‘one error in every hundred bits (10-5)’ transmitted.
    • User path - The path of the executable (exe) is created by the user for this module.

This is required when the user wants to link his program to this module.

A browse button is provided to get the required file from the system (Computer).

A file path viewer is also available to cross check the path of the inputted file.

Note: The User path is not stored in the external file, as the user program does not require it.

Programming

Pre-Conditions

    • The user has to program his code such that it accepts the input from a specific TEXT (Extension ‘Txt’) file and write the output to a specific TEXT (Extension ‘Txt’) file in the specified path, which is given at the left side of the screen.

Note: Both the input and the output should be along the path where ‘NetSim Application’ is installed.

    • The output should be in the specified format.

This format can be viewed by clicking the ‘Methodology’ button on the screen and under title ‘Output file format’.

Input/Output File Naming Criteria :

    • The User Linking Code begins with the Reading of the Inputs from the Input file.
    • The results of the code mentioned as per the Algorithm must be written into the Output file.
    • The Path of the input and the output file can be viewed in the Methodology screen of every coding program.
    • The file paths are displayed in the text box that is in the left side of the Methodology screen.
    • The complete code for file reading and writing is given in section marked “Code” below. One needs to take care that the correct paths are mentioned for writing the input.txt and output.txt file. – These path can be got by clicking on the P Button

Example: You would see a path like C:\Program Files\NetSim 2.0\input.txt Add additional “\” to make it C:\\Program Files\\NetSim 2.0\\input.txt Paste this path wherever input.txt is opened and read

Note:

The naming of the input and the output file must be same as the text displayed in the Methodology screen

There are two structures defined in this program. They are,

o ETHFRAME – This is a frame structure of the packets that has to be transmitted in the medium. This is maintained as a singly linked list.

The structure of ETHFRAME definition is as follows:

typedef struct ETHFRAME

{

int iseq; // Sequence number used for the sliding window concept

int ipack; // Packet number for the transmitting user packet

int iframe; // Frame number for the transmitting user packet

int ierrorcount; // Error count made for the frame

char szsrcaddr[20]; // Source address of the transmitting node

char szdestaddr[20]; // Destination address of the transmitting node

char szdata[1600]; // Frame value of the transmitting frame

struct ETHFRAME* nextframe; // Pointer to the next frame

} Eth_frame;

o NODE – This is the structure of the nodes that are configured in the network. This is maintained as a singly linked list.

The structure of NODE definition is as follows:

typedef struct NODE

{

char szname [20]; // name of the node

Eth_frame* txframe; // Transmitting list to be maintained

Eth_frame* rxframe; // Receiving list to be maintained

struct NODE* nextnode; // Pointer to the next node list

} Node;

Note: To start with variables of above described header file are initialized and contain no value.

After the execution of create_node (in-built function), the nodelist (global variable of type Node structure) will contain two references of node structure named "Node1" and "Node2".

Functions to be used (In-built functions)

There are three ‘In-built’ functions to be used for this module. These functions are defined in the header file "main.h" they are

create_node () – This function is used to create nodes and assigns necessary memory for each node.

This function creates two nodes, which are named ‘Node1’ and ‘Node2’

Work of Nodes -

‘Node1’ is the transmitting node. Node from which the inputted data is sent, and this node deletes the data that are transmitted successfully.

‘Node2’ is the receiving node. Node to which the inputted data is sent, and this node also sends acknowledgement to ‘Node1’ for the data received.

Note: Only the Nodes are created by this function, but the characteristics of the node like transmitting data, forming and transmitting acknowledgement should be programmed separately.

form_packet (char*) –This function is used to form the Packet frames.

This function form_packet (char*) – This function is used to form the Packet frames.

This function gets the number of characters available in the data text file and split them into frames of 1500 bytes each.

This function accepts a character pointer. This character pointer points to the data text file that is transmitted between‘Node1’ and ‘Node2’.

intro_error (int, Eth_frame*) – This function introduces error in the current frame transmitting.

This function accepts two input parameters, first is the Error probability rate (second parameter got from input file). Second is the reference of the current frame that is to be transmitted.

This function returns an integer value that gives the number of errors to be introduced in the frame.

Input / Output File Format

        Input File Content
This gives us the contents of the ‘Input. Txt’ from which the user has to get the values for his program

o File name – This is a string that contains the path of the text file given as input whose data is transmitted.

This is PASSED as an argument to the INBUILT function form_packet.

o Index – This is an integer that contains numerical value corresponding to the Error Probability Rate.

Note: A ‘delimiter ">"’ separates the above two values.

Input File Parsing

o This explains how to get values through ‘C’ program from ‘Input.Txt’.

o The user has to read the inputs from the ‘Input.Txt’ form the system.

o The file content (explained in Input File Content) has to be parsed and separated into two strings.

o In order to parse the strings and separate it into sub-strings, an INBUILT "C" function named strtok (defined in the string.h header file) is used.

o The separated sub string is sent as argument to the function mentioned in Input File Content.

Example:

FILE CONTENTS à c:\test.txt>2> -

This is stored in one character pointer szstr.

This szstr is set to the length of the file content.

FOR GETTING THE FILE NAME –

1.szfilename – strtok (szstr,">")

2.iindex – strtok (NULL,">").

Output File format

This gives us the format of Output. Txt’ to which the user has to write from his program

Each line should have four values. Each value should be separated by a delimiter‘>’.

There should be no extra white spaces or blank lines.

Example:

Value1>Value2>Value3>Value4>

Types:

There are five types of formats of writing in the output file.

Each format is written in specific condition, the types are explained below.

The condition of writing the types is explained in the algorithm.

Type1:

Value1 – "CNT",

Value 2 –output of the slidingcount function

Value 3 – "FRAMES"

Value 4 – "TRANSMIT"

Type2:

Value1 – "DT",

Value 2 –Frame number,

Value 3 – Frame’s Source address,

Value 4 – Frame’s Destination address.

Type3:

Value 1 – "EV",

Value 2 – Output of the intro_error function,

Value 3 – Frame’ Source address,

Value 4 – Frame’s Destination address.

Type4:

Value 1 – "ACK",

Value 2 – "POS",

Value 3 – Acknowledgement frame’s Source Address,

Value 4 – Acknowledgement frame’s Destination Address.

Type5:

Value 1 – "DEL"

Value 2 – count of frames being deleted

Value 3 – "FRAME"

Value 4 – "DELETED"

Note: The above convention to write into the ‘Output.Txt’ is mandatory.

Values in Quotes"" to be written into file ‘Output.Txt’ as it is including Case.

Example

Each line of the file must have four parameters as described; there should be no extra white spaces or blank lines. A sample file format of "14" frames transmitted from node1 to node2 with a window size of "7" is as follows:

CNT>7>FRAMES>TRANSMIT>

DT>1>node1>node2>

EV>0>node1>node2>

DT>2>node1>node2>

EV>0>node1>node2>

DT>3>node1>node2>

EV>0>node1>node2>

DT>4>node1>node2>

EV>0>node1>node2>

DT>5>node1>node2>

EV>0>node1>node2>

DT>6>node1>node2>

EV>0>node1>node2>

DT>7>node1>node2>

EV>0>node1>node2>

ACK>POS>node2>node1>

DEL>7>FRAME>DELETED>

CNT>7>FRAMES>TRANSMIT>

DT>8>node1>node2>

EV>0>node1>node2>

DT>9>node1>node2>

EV>1>node1>node2>

DT>10>node1>node2>

EV>0>node1>node2>

DT>11>node1>node2>

EV>0>node1>node2>

DT>12>node1>node2>

EV>0>node1>node2>

DT>13>node1>node2>

EV>0>node1>node2>

DT>14>node1>node2>

EV>0>node1>node2>

ACK>POS>node2>node1>

DEL>1>FRAME>DELETED>

CNT>1>FRAMES>TRANSMIT>

DT>9>node1>node2>

EV>0>node1>node2>

ACK>POS>node2>node1>

DEL>6>FRAME>DELETED>

In the above sample file:

Frames 1 to 7 are transmitted in a single window. Since all the "7" frames are transmitted successfully, a single positive ACK is transmitted from node2 to node1 after the transmission of the 7 frames. Therefore seven frames are deleted in the node1's transmission list and the acknowledgement frame in the node2's transmission list is also deleted.

Frames 8 to 14 are transmitted next from node1 to node2. Out of these Frame 9 generates an error and the rest are transmitted successfully. Hence an acknowledgement is transmitted for frame 8 from node2 to node1. A cumulative positive acknowledgement for the frames 10 to 14 is stored as ACK14. Therefore frame 8 is deleted from node1's transmission list by receiving the positive acknowledgement for the frame 8.The acknowledgement for frame 8 is deleted from node2's transmission list.

After this only Frame9 is retransmitted. After the successful transmission of the frame, a positive acknowledgement for Frame 9 is formed and as receiver has ACK14, cumulative acknowledgment ACK 14 is transmitted from node2 to node1. The acknowledgement is deleted from node2's transmission list. On receiving the acknowledgement, the frames 9 to 14 are deleted from node1's transmission list, and the window slides by 5 frames.

In this process the fourteen frames are to be transmitted using Selective Repeat Transmission flow control protocol with a window size of seven ("7"); however because of the error in the 9th frame total number of transmission increases to 18.

Note the difference in the total number of transmission in the GOBACKN and SELECTIVE REPEAT Sliding Window Protocol.

Algorithm

1. Parse the Input.txt file and store the data file path and index from the file. The index value represents the Error Probability value that is set for the network. Store the value in the local variable err.

2. Call the in built function create_node. Create two nodes for the network.

3. Call the in built function form_packet and pass data file path, which is got by parsing the file Input.txt.

SELECTIVE REPEAT PROCESS --

1. Initialize contents of the buffer szBuffer( its functionality is explained below) to 0 and Global variable nCurrentFrame as 0(Current frame that has to be transmitted in the window).

2. Repeat the loop until the transmission list of the transmitting node becomes empty. (i.e.) Transmission list of the node1 becomes empty.

1. Get the current first frame of the transmission list of the transmitting node.

2. Call the fnFrameCount (function returns the frame count i.e. the number of frames that is to be transmitted in the current window, as explained below) and store the return value in the local variable islindex. Write the contents into a fresh (new) output file "output.txt" as TYPE1.

3. Repeat the loop from 1 to the islindex

1. Write the current frame referred into output file "output.txt" as Type2.

2. Call the inbuilt function intro_error with the ErrorValue and the current frame and store the return value in the local variable iret.

3. Write the contents into the output file "output.txt" as Type3.

4. If the iret value is 0 (No Error Condition)

1.3.4.1. make the buffer content of szBuffer as 1. I.e. szBuffer[(transframeà iseq) – 1] = 1.

5. Get the next frame of the transmitting list of the transmitting node i.e. the node is "node1".

6. Form the acknowledgement frame. If acknowledgment frame is not equal to NULL

1. Write the content into the output file "output.txt" as Type4.

2. Delete the current acknowledgement frame from the transmission list of the receiving node i.e. the node "node2".

3. Write the content into the output file "output.txt" as Type5, i.e. the number of frames deleted in the loop.

ACKNOWLEDGEMENT PROCESS

1. Store the received node reference in the local variable.

2. If frame is transmitted with error

2.1. do not form acknowledgment.

3. Else if frame is transmitted without error

1. Increment cCount value

2. Repeat till number of frames received

1. If szBuffer value is 0, Make nCurrentFrame equal to nLoop value and break the loop.

2. Else if szBuffer value is not 0, increment the value of cCount.

3. If all frames in window are transmitted, then make the nCurrentFrame and szBuffer values to 0.

4. Form a new acknowledgment frame with its iseq variable value equal to cCount.

szBuffer array— It is of size szBuffer[7]

This is a buffer used to store whether the corresponding frame is transmitted with error or without error. With error is represented with 0 and without error by 1.

fnFrameCount FUNCTION

This function returns the frame count i.e. the number of frames that is to be transmitted in the current window. This function returns an integer value that gives the number of frames that is to be transmitted in the current continuous transmission.

Pseudo code

The pseudo code / algorithm is given below for selective repeat flow control.

// Store Transmission list of the source node to the local Eth_frame variable.

framelist = nodelist->txframe;

for iloop= 0 - 7

szBuffer[iloop] = 0;

// Make the nCurrentFrame as 0, That is the first frame of the window is going to be transmitted

nCurrentFrame = 0;

// Repeat the loop until all the frames has been transmitted in the network

while nodelist->txframe != NULL

BEGIN

icount = 0;

//Get the first frame for the transmission

transframe = call function retseltxframe(-1,-1);

// Get the count of number of frames to be transmitted in the medium

isliindex = call function fnFrameCount();

// Write the Slinding Window count into the output file.

fp = fopen(szfilename,"a+");

fprintf(fp,"CNT>%d>FRAMES>TRANSMIT>\n",isliindex);

fclose(fp);

ialreadyerror = 0;

for iloop = 0 – isliindex

BEGIN

// Store the temporary packet number, frame number in the local variable

ipackno=transframe->ipack;

iframeno=transframe->iframe;

//Write the data Value into the output file.

fp = fopen(szfilename,"a+");

fprintf(fp,"DT>%d>%s>%s>\n",transframe->iframe,transframe->szsrcaddr,transframe->szdestaddr);

fclose(fp);

iret = call function intro_error(nErrValue,transframe);

fp = fopen(szfilename,"a+");

fprintf(fp,"EV>%d>%s>%s>\n",iret,transframe->szsrcaddr,transframe->szdestaddr);

fclose(fp);

If iret == 0 //No Error in the frame

szBuffer[(transframe->iseq) - 1] = 1;

// Call the function to get the next transmission frame

transframe= call function retseltxframe(ipackno,iframeno);

END

// Store the transmission back to the original position

nodelist->txframe = framelist;

//Formation of the acknowledgement

call function formselack();

// Get the acknowledgement frame of the transmission

ackframe = call function retselackframe();

if ackframe != NULL

BEGIN

fp = fopen(szfilename,"a+");

fprintf(fp,"ACK>POS>%s>%s>\n",ackframe->szsrcaddr,ackframe->szdestaddr);

fclose(fp);

// Loop to delete the frames

For iloop=0 - ackframe->iseq framelist=delseltxframe();

fp = fopen(szfilename,"a+");

fprintf(fp,"DEL>%d>FRAME>DELETED>\n",ackframe->iseq);

fclose(fp);

}

END

END

Code

Copy the code on to your C\C++ editor. Write your own code where you see “Write your code here”. The pseudo code / algorithm is as given above

# include

# include

# include

# include

# define POSACKDATA "POSITIVEPOSITIVEPOSITIVEPOSITIVEPOSITIVEACKACK"

# define NEGACKDATA "NEGATIVENEGATIVENEGATIVENEGATIVENEGATIVEACKACK"

unsigned long g_ulnErrorSeed1 = 12345678;

unsigned long g_ulnErrorSeed2 = 23456781;

double idata = 0.00;

int nCurrentFrame;

char szBuffer[8];

// A general Ethernet frame structure for making the transmission

typedef struct ETHFRAME

{

int iseq;// Sequence used for the sliding window concept

int ipack;// Packet number for the transmitting user packet

int iframe;// Frame number for the transmitting user packet

int ierrorcount;// Error count to be made for the frame,Maxium retry value for the frame

char szsrcaddr[20];// source address of the transmitting node

char szdestaddr[20];// Destination address of the transmitting node

char szdata[1600];// frame value of the transmitting frame

struct ETHFRAME* nextframe;// Pointer to the next frame

}Eth_frame;

// A general Node details structure that are to be configured in the network

typedef struct NODE

{

char szname[20];// name of the node

Eth_frame* txframe;// Transmitting list to be maintained

Eth_frame* rxframe;// Receiving list to be maintained

struct NODE* nextnode;// Pointer to the next node list

}Node;

// A global variable that has the node details that are configured in the network

Node* nodelist = NULL;

int nerrValue = 0; // Holds the Error Probability Rate.

char szstr[500]; // Local string variable to get file content.

char sztype[500]; // Local string variable to hold the Error Probability Rate Index.

char* sztemp = NULL; // Local string pointer to store the parsed string got from the file.

char szfilename[250]; // Local variable to store the file name that has to splitted into frames.

FILE* fp = NULL; // A file pointer to hold the reference for a file.

// Define a FILE pointer variable

// FILE* fp=NULL;

// A three local variables to hold the reference of the frame of type Eth_frame

Eth_frame* framelist = NULL;

Eth_frame* transframe=NULL;

Eth_frame* ackframe=NULL;

int isliindex = 0;// Useful for getting Number of frames to be transmitted in the window.

int iret = 0;// A local variable to get the Return value of the function intro_error (Function in "main.h").

int ipackno = 0,iframeno=0; // A local variables to hold the packet and the frame number of the Current frame.

int iloop = 0; // A local looping variable

int ialreadyerror = 0;// A Error flag value

int icount = 0;// A local counter variable.

// Define a character pointer for making the filename

// char szfilename[250];

long double g_lfnRandomNo(long double ldBER)

{

long lx = 0;

long double ldy = 0;

long double ltemp;

g_ulnErrorSeed1 = (unsigned long)((40014 * g_ulnErrorSeed1) % (unsigned long)(2147483563));

g_ulnErrorSeed2 = (unsigned long)((40692 * g_ulnErrorSeed2) % (unsigned long)(2147483399));

lx = (long)((g_ulnErrorSeed1 - g_ulnErrorSeed2) % (long)(2147483562));

if (lx != 0)

{

ldy = (long double)((long double)(lx) / (long double)(2147483563));

}

else

{

ldy = (long double)((long double)(2147483562) / (long double)(2147483563));

}

ldy = ldy * 100000000;

ltemp = (long double)(fmod(ldy, (ldBER+1)));

return ltemp;

}

int g_fnDecideError(char cBER, short int snPacketSize)

{

float fEpsilon = 0.0;

int nPacketBits = 0;

double dPacketnoerror ;

double dPEP;

long double ldRandomNumber;

long double ldBER;

float fRand;

switch (cBER)

{

case 2:

ldBER = 100;

break;

case 3:

ldBER = 1000;

break;

case 4:

ldBER = 10000;

break;

case 5:

ldBER = 100000;

break;

case 6:

ldBER = 1000000;

break;

case 7:

ldBER = 10000000;

break;

case 8:

ldBER = 100000000;

break;

case 9:

ldBER = 1000000000;

break;

case 0:

return 0;

}

fEpsilon = (float)(1/(1.0*ldBER));

nPacketBits = snPacketSize * 8;

dPacketnoerror = (double)(pow((1-fEpsilon),nPacketBits));

dPEP = (double)(1-dPacketnoerror);

ldRandomNumber = g_lfnRandomNo(ldBER);

fRand = (float) (ldRandomNumber /(1.0*ldBER));

if (fRand <= dPEP)

{

return 1;

}

else //if(fRand>dPEP)

{

return 0;

}

}

// A function to configure the network

void create_node()

{

Node* tempnode=NULL;

Node* tempnode1=NULL;

tempnode=(Node *)malloc(sizeof(Node *));

tempnode->rxframe = NULL;

tempnode->txframe = NULL;

tempnode->nextnode = NULL;

idata = 0.00;

if(nodelist!= NULL)

{

free(nodelist);

nodelist = NULL;

}

if(nodelist == NULL)

{

strcpy(tempnode->szname ,"node1");

nodelist = tempnode ;

}

tempnode=NULL;

tempnode=(Node *)malloc(sizeof(Node *));

tempnode->rxframe = NULL;

tempnode->txframe = NULL;

tempnode->nextnode = NULL;

strcpy(tempnode->szname ,"node2");

tempnode1 = nodelist;

while(tempnode1 ->nextnode != NULL)

{

tempnode1 = tempnode1->nextnode ;

}

tempnode1 ->nextnode = tempnode;

}

int form_packet(char* szstr1)

{

int iwinsize = 7;

Eth_frame *parse_frame = NULL;

Eth_frame *traverseframe = NULL;

FILE* fp = NULL;

char szstr[1600];

int iloop = 0;

int icount = 0,icount1 = 1;

fp=fopen(szstr1,"r");

while(!feof(fp))

{

szstr[iloop++]=(char)fgetc(fp);

szstr[iloop]='\0';

if(iloop>1500)

{

parse_frame=(Eth_frame *)malloc(sizeof(Eth_frame));

iloop=0;

icount++;

parse_frame->ipack = 1;

parse_frame->ierrorcount = 1;

parse_frame->iframe = icount;

if(icount1 <= 7)

{

parse_frame->iseq = icount1;

icount1++;

}

else

{

icount1=1;

parse_frame ->iseq = icount1;

icount1++;

}

strcpy(parse_frame ->szsrcaddr ,"node1");

strcpy(parse_frame->szdestaddr ,"node2");

strcpy(parse_frame->szdata,szstr);

parse_frame->nextframe = NULL;

if(nodelist->txframe == NULL)

{

nodelist->txframe = parse_frame;

}

else

{

traverseframe = nodelist->txframe;

while(traverseframe ->nextframe != NULL)

{

traverseframe=traverseframe->nextframe;

}

traverseframe->nextframe = parse_frame;

}

}

else

{

}

}

fclose(fp);

if(iloop!=0)

{

parse_frame=(Eth_frame *)malloc(sizeof(Eth_frame));

icount++;

parse_frame->ipack = 1;

parse_frame->ierrorcount = 1;

parse_frame->iframe = icount;

if(icount1 <= 7)

{

parse_frame->iseq = icount1;

icount1++;

}

else

{

icount1=1;

parse_frame ->iseq = icount1;

icount1++;

}

strcpy(parse_frame ->szsrcaddr ,"node1");

strcpy(parse_frame->szdestaddr ,"node2");

strcpy(parse_frame->szdata,szstr);

parse_frame->nextframe = NULL;

if(nodelist->txframe == NULL)

{

nodelist->txframe = parse_frame;

}

else

{

traverseframe = nodelist->txframe;

while(traverseframe ->nextframe != NULL)

{

traverseframe=traverseframe->nextframe;

}

traverseframe->nextframe = parse_frame;

}

}

else

{

}

traverseframe=nodelist->txframe;

return icount;

}

int intro_error (int nErrorRate,Eth_frame* transpacket)

{

// Define a variable to get the length of the string

double dlength = 0.00;

dlength=0;

dlength+=10;// Source Address + Destination Address + Length or type of the frame

dlength+=(double)strlen(transpacket->szdata);// Length of the Data

return(g_fnDecideError(nErrorRate,(short int)dlength));

}

int slidingcount()

{

int iret = 0;

Eth_frame* traverseframe=NULL;

traverseframe=nodelist->txframe;

traverseframe=traverseframe->nextframe;

iret++;

while(traverseframe!=NULL)

{

if(traverseframe==NULL)

break;

else

{

iret++;

if(iret == 8)

{

iret = 7;

break;

}

}

traverseframe = traverseframe->nextframe;

}

return iret;

}

int fnFrameCount()

{

// Define a local variable for holding the transmitting frame list

Eth_frame* retframe = NULL;

// Define check count variable

int nCount = 0;

// Define a Return variable

int nReturn = 0;

// Define a Loop variable

int nLoop = 0;

// Define a character variable

char cChar = 0;

// Loop to find any frame in the window has reached the destination

for(nLoop=nCurrentFrame;nLoop<7;nloop++)

{

if(szBuffer[nLoop] != 0)

{

// Make the flag value as 1 that denotes some frame has been transmitted before the window

cChar = 1;

break;

}

else

{

// Increment the nReturn value

nReturn++;

}

}

if(cChar == 1)

{

// Only that has to be transmitted in the window

return 1;

}

else

{

// Assign the transmission list to the local variable

retframe = nodelist->txframe;

// Check the transmission list has that much amount of frame

for(nLoop=0;nLoop

{

if(retframe==NULL)

break;

else

{

// Surely first frame is there.

nCount++;

// Move the frame pointer to the next node

retframe=retframe->nextframe;

}

}

// Assign the Counter to the local variable

nReturn = nCount;

// Number of frames that has to be transmitted in the window

return nReturn;

}

}

Eth_frame* retseltxframe(int ipackno,int iframeno)

{

// Define a Local variable

Eth_frame* retframe=NULL;

// Assign the Sender node transmission list to the local variable

retframe = nodelist->txframe;

if(ipackno==-1 && iframeno == -1)

return retframe;

else

{

while(retframe != NULL)

{

if(retframe->ipack == ipackno && retframe->iframe == iframeno)

break;

retframe = retframe->nextframe;

}

if(retframe->nextframe == NULL)

return NULL;

else

return retframe->nextframe;

}

}

Eth_frame* delseltxframe()

{

Eth_frame* traverseframe = NULL; //Variable of type Eth_frame

traverseframe=nodelist->txframe; //Source node Transmission list reference.

if(traverseframe->nextframe == NULL)//Single frame in the list.

nodelist->txframe = NULL; //Make the Transmission list of the

//source node empty.

else

//Make the Transmission list of the source node to be pointed to the

//next frame of the list.

nodelist->txframe=nodelist->txframe->nextframe;

// Return the final Transmission list of the source node.

return nodelist->txframe;

}

void formselack()

{

// A function to form the acknowledgement frame in the

Node* acknode = NULL;

Eth_frame* ackframe=NULL;

int nLoop = 0;// Looping Variable

int cCount = 0;// Counting Variable

int cFlag = 0;

// Store the received node reference in the local variable

acknode = nodelist->nextnode;

if(szBuffer[nCurrentFrame] == 0)// Error in the frame so don't form any acknowledgement

{

acknode->txframe = NULL;

}

else// Current frame is Correct

{

// Increment the Received frame by 1

cCount++;

// Loop to count how many frames has been received

for(nLoop=(nCurrentFrame+1);nLoop<7;nloop++)

{

if(szBuffer[nLoop] == 0)

{

// Make the nCurrentFrame as nLoop

nCurrentFrame=nLoop;

break;

}

else

{

// Increment The Received Count by 1.

cCount++;

}

}

if(nLoop == 7)// All frames has been transmitted in the window

{

nCurrentFrame = 0;// Make the Index to 0.

// Initialize the received buffer to 0

for(nLoop=0;nLoop<7;nloop++)

{

szBuffer[nLoop] = 0;

}

}

// Create a new acknowledgement frame

ackframe = (Eth_frame *)malloc(sizeof(Eth_frame));

ackframe->iseq = cCount;

strcpy(ackframe->szsrcaddr,"node2");

strcpy(ackframe->szdestaddr,"node1");

strcpy(ackframe->szdata,POSACKDATA);

ackframe->nextframe = NULL;

acknode->txframe = ackframe;

}

}

Eth_frame* retselackframe()

{

Node* acknode = NULL;

acknode=nodelist->nextnode;

return acknode->txframe;

}

void delselackframe()

{

Node* acknode=NULL;

Eth_frame* ackframe=NULL;

Eth_frame* traverseframe=NULL;

Eth_frame* traverseframe1=NULL;

acknode=nodelist->nextnode;

if(acknode->txframe->nextframe == NULL)

acknode->txframe = NULL;

else

acknode->txframe=acknode->txframe->nextframe;

}

void fnSelRepReadInput()

{

/*

Open the Input file input.txt.

This has the inputs that you have made in the front end.

The input.txt file is present in the Application path where the NETSIM is installed.

The path of the input.txt is specified in the V.B. Steps for getting the path

1. Click the Methodology button.

2. In the left hand side of the screen there are two file paths specified

3. The first one has the filename Input.txt (The file that has the user inputs)

4. The second one has the filename Output.txt (The file in which the user has to write his outputs)

Note:

The naming of the input and the output file

must be same as the text displayed in the

Methodology screen.

Consider the Application is Installed in c:\\netsim

*/

// Open the Input file and get the string into the local variable

fp=fopen("E:\\SR\\input.txt","r");

fgets(szstr,250,fp);

fclose(fp);

// ------ Parsing Technique ----------------

// First string parsed with strtok (inbuilt function)

sztemp=strtok(szstr,">");

// First parameter has the filename that has to be transmitted from the source to the destination

// Parsed string reference is stored in the local variable szfilename

strcpy(szfilename,sztemp);

// Parse the remaining string to get the Error Probability Error index

// Parse string is stored in the local variable sztype

sztemp=strtok(NULL,">");

strcpy(sztype,sztemp);

}

void SelRepeat(int nErrValue)

{

//

Write your code here

//

}

void main()

{

fnSelRepReadInput();

// Call the function defined in the default header file main.h

create_node();

// Call the function defined in the default header file main.h

form_packet(szfilename);

// Call the function defined in the default header file main.h

// The return value is stored in the local variable derrvalue

nerrValue = atoi(sztype);

// User defined code for Selective Repeat

// Code defined in the user defined

// This szfilename variable has the output file path where the user has to write his output

strcpy(szfilename,"E:\\SR\\output.txt");

fp = fopen(szfilename,"w");

fclose(fp);

SelRepeat (nerrValue);

}

Link State Routing

Concept

· The main goal here is to find the shortest route between two vertices (nodes) in the given graph.

· The algorithm used is called "Dijkstra’s algorithm"

· A graph is a collection of vertices (nodes) and edges.

· A vertex (node) is connected to another using an edge.

· The weight of the edge may be represented as distance, cost, time, etc depending upon the problem given.

How to write you own code

9;

In the Sample mode, you have to select the required algorithm, enter the input data and click the button on the screen to view the results.

Whereas in User mode, you have to write your own program in the c/ C++, compile and link to NetSim software for validation. #9;

Click on the button to view the file path.

Note: The naming of the input and the output file must be same as the text displayed on the screen.

How to link your code 9;

To link your code, click on the button to obtain the screen for retrieving the file path.

Click on browse button and find the path where you have your C/C++ file (.exe) stored. The .exe will be found in the "Debug" folder of your source code. Click OK after your .exe file is selected. Select the required Algorithm and enter the input data file. Click the button to view the output.

Copy the program given in "Code" below to the C++ complier and write your own code in the space written as " Write your code here".

Input/Output File Naming Criteria:

The User Linking Code begins with the Reading of the Inputs from the Input file.

The results of the code mentioned as per the Algorithm must be written into the Output file.

The Path of the input and the output file can be viewed in the Methodology screen of every coding program.

Pre-Conditions

You have to program your code such that it accepts the input from a specific TEXT (Extension ‘Txt’) file and write the output to a specific TEXT (Extension ‘Txt’) file in the specified path, which is given at the left side of the screen.

Note: Both the input and the output should be along the path where ‘NetSim Application’ is installed.

One needs to take care that the correct paths are mentioned for writing the input.txt and output.txt file. – These path can be got by clicking on the Button

Example: You would see a path like C:\Program Files\NetSim 2.0\input.txt Add additional "\" to make it C:\\Program Files\\NetSim 2.0\\input.txt Paste this path wherever input.txt is opened and read

Dijkstra’s Algoithm : Pseudo Code

Open the input file, read the contents of the files and store them in local variables for further calculation.

While iFlag is false:

Initialize the min and node value as –1

For i = 0 to iNo – 1(iNo – Number of nodes – Got from the input file)

If include [i] = 0

if min = -1

min = distance [ i ]

node = I

else

if distance [i] <>

min = distance [i]

node = I

if node != -1

include [i] = 1

if min != -1

For i = 0 to iNo – 1 (iNo – Number of nodes – Got from the input file)

if include [i] == 0

if distanceMatrix [i][node] = -1 // do nothing

else

if distance[node]=-1 and distance[I]=-1 // do nothing

if distance[i] = -1

distance[i] = distance[node] + distanceMatrix [i][node]

path[i] = node

else if distance[node] + distanceMatrix[i][node]) <>

distance[i] = distance[node] + distanceMatrix[i][node]

Code

Copy the code on to your C / C++ editor. Write your own code where you see "Write your code here". The pseudo code / algorithm is as given above

# include

# include

# include

# include

// Global variable

int distance[10]; // Array to store the distance from source to destination

int path[10]; // Array for storing the Path from source to a particular destination

int include[10]; // Flag array for storing whether a particular node has been included or not.

int source; // To store the source node

int destination; // to store the destination node

bool iFlag; // Iteration Flag

int min; // to store out the minimum node distance

int node; // To keep track of the minimum node

int distanceMatrix[10][10]; // This matrix should be initialized by '-1' for all the fields.

int i,j,iNo;

//This is the main for finding out Shortest Path using Dijkstra's Algorithm

void fnDijkstra();

void fnReadDijkstrasInput(); // Input file reading

void fnWriteDijkstrasOutput(); // Output file writing

void main()

{

fnReadDijkstrasInput();//Function to read the input from a text file written from NetSim.

// This function definition is available in the Function.h header file.

//If user wants to use this function the header should be included to the program

fnDijkstra();

fnWriteDijkstrasOutput();//Function to write the output in a text file for NetSim.

// This function defenition is avaliable in the Function.h header file.

//If user wants to use this function the header should be included to the program

}

void fnDijkstra()

{

// Initializing the Path Array and The Include Array

// For Include Array

for (i=0;i

{

if (i==source) // when nodes are the same eg. (1,1) no edge exists

include[i]=1;

else

include[i]=0;

}//end of for loop

// For Distance Array

for (i=0;i

{

if(i==source)

distance[i]=0;

else

{

if (distanceMatrix[source][i] == -1)

distance[i] = -1;

else

distance[i] = distanceMatrix[source][i];

}

}//end of for loop

// For Initialising Path Array

for (i=0;i

{

if (distanceMatrix[source][i] == -1)

path[i]=-1;

else

path[i]=source;

}//end of for loop

iFlag = false;

//main iteration phase for Dijkstra's Algorithm

while( iFlag == false)

//

Write your code here

//Checking if all the nodes has been included.

for(i=0;i

{

iFlag = true;

if (include[i] == 0)

{

iFlag = false;

break;

}

}

}//end of while (!iFlag)

}

void fnReadDijkstrasInput()

{

char szString[80]; // Varaible - to get each line read from the file

char* szToken; // Variable - to parse the file contents

FILE* fp; // File pointer

/*

Open the Input file input.txt.

This has the inputs that you have made in the front end.

The input.txt file is present in the Application path where the NETSIM is

installed.

The path of the input.txt is specified in the V.B. Steps for getting the path

1. Click the Methodology button.

2. In the left hand side of the screen there are two file paths specified

3. The first one has the filename Input.txt(The file that has the user inputs)

4. The second one has the filename Output.txt (The file in which the user has

to write his outputs)

Note:

The naming of the input and the output file

must be same as the text displayed in the

Methodology screen.

Consider the Application is Installed in c:\\NetSim

*/

// Open the input file for Reading

fp = fopen("C:\\Program Files\\NetSim 2.0\\input.txt","r");

fgets(szString,80,fp);

szToken = new char(31);

szToken = strtok(szString,">");

szToken = strtok( NULL, ">" );

iNo = atoi(szToken); // Storing the number of nodes present in the graph

// Initializing the Distance Matrix

for(i=0;i

{

for(j=0;j

{

distanceMatrix[i][j] = -1;

}

}

//parsing the input file and storing the values into distance matrix

for (i=0;i

{

fgets(szString,80,fp);

szToken=strtok(szString,">");

j=0;

while( szToken != NULL )

{

/* While there are tokens in "string" */

if (atoi(szToken) == -1)

{ // Do Nothing

}

else // To make a Adjacency Matrix

{

distanceMatrix[i][j]=atoi(szToken);

//distanceMatrix[j][i]=atoi(szToken);

}

/* Get next token: */

j++;

szToken = strtok( NULL, ">" );

}

}

// Tokenizing next two line for storing the source and destination node

// Tokenizing for the source node

fgets(szString,80,fp);

szToken=strtok(szString,">");

szToken=strtok(NULL,">");

source = atoi(szToken); // source node

--source;

// Tokenizing for the destination node

fgets(szString,80,fp);

szToken=strtok(szString,">");

szToken=strtok(NULL,">");

destination = atoi(szToken); // Destination Node

--destination;

fclose(fp);

}

void fnWriteDijkstrasOutput()

{

FILE *fpOutput=NULL;

// To generate the output file into 'output.txt

fpOutput=fopen("C:\\Program Files\\NetSim 2.0\\output.txt","w");

// Print the distance Array

fprintf(fpOutput,"Distance>");

for(i=0;i

fprintf(fpOutput,"%d>",distance[i]);

// Print the Path Arrray

fprintf(fpOutput,"\nPath>");

for(i=0;i

fprintf(fpOutput,"%d>",path[i]+1);

fclose(fpOutput);

}

Link State Routing

Concept

· The main goal here is to find the shortest route between two vertices (nodes) in the given graph.

· The algorithm used is called "Dijkstra’s algorithm"

· A graph is a collection of vertices (nodes) and edges.

· A vertex (node) is connected to another using an edge.

· The weight of the edge may be represented as distance, cost, time, etc depending upon the problem given.

How to write you own code

9;

In the Sample mode, you have to select the required algorithm, enter the input data and click the button on the screen to view the results.

Whereas in User mode, you have to write your own program in the c/ C++, compile and link to NetSim software for validation. #9;

Click on the button to view the file path.

Note: The naming of the input and the output file must be same as the text displayed on the screen.

How to link your code 9;

To link your code, click on the button to obtain the screen for retrieving the file path.

Click on browse button and find the path where you have your C/C++ file (.exe) stored. The .exe will be found in the "Debug" folder of your source code. Click OK after your .exe file is selected. Select the required Algorithm and enter the input data file. Click the button to view the output.

Copy the program given in "Code" below to the C++ complier and write your own code in the space written as " Write your code here".

Input/Output File Naming Criteria:

The User Linking Code begins with the Reading of the Inputs from the Input file.

The results of the code mentioned as per the Algorithm must be written into the Output file.

The Path of the input and the output file can be viewed in the Methodology screen of every coding program.

Pre-Conditions

You have to program your code such that it accepts the input from a specific TEXT (Extension ‘Txt’) file and write the output to a specific TEXT (Extension ‘Txt’) file in the specified path, which is given at the left side of the screen.

Note: Both the input and the output should be along the path where ‘NetSim Application’ is installed.

One needs to take care that the correct paths are mentioned for writing the input.txt and output.txt file. – These path can be got by clicking on the Button

Example: You would see a path like C:\Program Files\NetSim 2.0\input.txt Add additional "\" to make it C:\\Program Files\\NetSim 2.0\\input.txt Paste this path wherever input.txt is opened and read

Dijkstra’s Algoithm : Pseudo Code

Open the input file, read the contents of the files and store them in local variables for further calculation.

While iFlag is false:

Initialize the min and node value as –1

For i = 0 to iNo – 1(iNo – Number of nodes – Got from the input file)

If include [i] = 0

if min = -1

min = distance [ i ]

node = I

else

if distance [i] <>

min = distance [i]

node = I

if node != -1

include [i] = 1

if min != -1

For i = 0 to iNo – 1 (iNo – Number of nodes – Got from the input file)

if include [i] == 0

if distanceMatrix [i][node] = -1 // do nothing

else

if distance[node]=-1 and distance[I]=-1 // do nothing

if distance[i] = -1

distance[i] = distance[node] + distanceMatrix [i][node]

path[i] = node

else if distance[node] + distanceMatrix[i][node]) <>

distance[i] = distance[node] + distanceMatrix[i][node]

Code

Copy the code on to your C / C++ editor. Write your own code where you see "Write your code here". The pseudo code / algorithm is as given above

# include

# include

# include

# include

// Global variable

int distance[10]; // Array to store the distance from source to destination

int path[10]; // Array for storing the Path from source to a particular destination

int include[10]; // Flag array for storing whether a particular node has been included or not.

int source; // To store the source node

int destination; // to store the destination node

bool iFlag; // Iteration Flag

int min; // to store out the minimum node distance

int node; // To keep track of the minimum node

int distanceMatrix[10][10]; // This matrix should be initialized by '-1' for all the fields.

int i,j,iNo;

//This is the main for finding out Shortest Path using Dijkstra's Algorithm

void fnDijkstra();

void fnReadDijkstrasInput(); // Input file reading

void fnWriteDijkstrasOutput(); // Output file writing

void main()

{

fnReadDijkstrasInput();//Function to read the input from a text file written from NetSim.

// This function definition is available in the Function.h header file.

//If user wants to use this function the header should be included to the program

fnDijkstra();

fnWriteDijkstrasOutput();//Function to write the output in a text file for NetSim.

// This function defenition is avaliable in the Function.h header file.

//If user wants to use this function the header should be included to the program

}

void fnDijkstra()

{

// Initializing the Path Array and The Include Array

// For Include Array

for (i=0;i

{

if (i==source) // when nodes are the same eg. (1,1) no edge exists

include[i]=1;

else

include[i]=0;

}//end of for loop

// For Distance Array

for (i=0;i

{

if(i==source)

distance[i]=0;

else

{

if (distanceMatrix[source][i] == -1)

distance[i] = -1;

else

distance[i] = distanceMatrix[source][i];

}

}//end of for loop

// For Initialising Path Array

for (i=0;i

{

if (distanceMatrix[source][i] == -1)

path[i]=-1;

else

path[i]=source;

}//end of for loop

iFlag = false;

//main iteration phase for Dijkstra's Algorithm

while( iFlag == false)

//

Write your code here

//Checking if all the nodes has been included.

for(i=0;i

{

iFlag = true;

if (include[i] == 0)

{

iFlag = false;

break;

}

}

}//end of while (!iFlag)

}

void fnReadDijkstrasInput()

{

char szString[80]; // Varaible - to get each line read from the file

char* szToken; // Variable - to parse the file contents

FILE* fp; // File pointer

/*

Open the Input file input.txt.

This has the inputs that you have made in the front end.

The input.txt file is present in the Application path where the NETSIM is

installed.

The path of the input.txt is specified in the V.B. Steps for getting the path

1. Click the Methodology button.

2. In the left hand side of the screen there are two file paths specified

3. The first one has the filename Input.txt(The file that has the user inputs)

4. The second one has the filename Output.txt (The file in which the user has

to write his outputs)

Note:

The naming of the input and the output file

must be same as the text displayed in the

Methodology screen.

Consider the Application is Installed in c:\\NetSim

*/

// Open the input file for Reading

fp = fopen("C:\\Program Files\\NetSim 2.0\\input.txt","r");

fgets(szString,80,fp);

szToken = new char(31);

szToken = strtok(szString,">");

szToken = strtok( NULL, ">" );

iNo = atoi(szToken); // Storing the number of nodes present in the graph

// Initializing the Distance Matrix

for(i=0;i

{

for(j=0;j

{

distanceMatrix[i][j] = -1;

}

}

//parsing the input file and storing the values into distance matrix

for (i=0;i

{

fgets(szString,80,fp);

szToken=strtok(szString,">");

j=0;

while( szToken != NULL )

{

/* While there are tokens in "string" */

if (atoi(szToken) == -1)

{ // Do Nothing

}

else // To make a Adjacency Matrix

{

distanceMatrix[i][j]=atoi(szToken);

//distanceMatrix[j][i]=atoi(szToken);

}

/* Get next token: */

j++;

szToken = strtok( NULL, ">" );

}

}

// Tokenizing next two line for storing the source and destination node

// Tokenizing for the source node

fgets(szString,80,fp);

szToken=strtok(szString,">");

szToken=strtok(NULL,">");

source = atoi(szToken); // source node

--source;

// Tokenizing for the destination node

fgets(szString,80,fp);

szToken=strtok(szString,">");

szToken=strtok(NULL,">");

destination = atoi(szToken); // Destination Node

--destination;

fclose(fp);

}

void fnWriteDijkstrasOutput()

{

FILE *fpOutput=NULL;

// To generate the output file into 'output.txt

fpOutput=fopen("C:\\Program Files\\NetSim 2.0\\output.txt","w");

// Print the distance Array

fprintf(fpOutput,"Distance>");

for(i=0;i

fprintf(fpOutput,"%d>",distance[i]);

// Print the Path Arrray

fprintf(fpOutput,"\nPath>");

for(i=0;i

fprintf(fpOutput,"%d>",path[i]+1);

fclose(fpOutput);

}

Data Encryption Standard

Concept Data encryption works on binary numbers. The standard of Data encryption is a block cipher, which means it operates on a plain text of size 64 bits, and returns a block of the same size.

There are two processes in a data encryption standard:

    1. Key generation process
    2. Data encryption process

User inputs:

    1. The key text used for encryption should be of exactly 16 hexadecimal characters.
    2. Select the number of iteration.
    3. Enter a maximum of 1500 characters.
    4. After the data has been entered, the type of operation – whether encryption or decryption –user program or sample program – has to be chosen, the type of program to be linked and the key text entered, you can view the output by clicking ‘LINK’.

Programming You can write your own program for encryption and decryption and you can verify this using the graphical user interface.

Pre-conditions:

    1. A user-written program should read the value from the ‘Input.txt’ in the application path which has input from the GUI at runtime
    2. The output should be stored in ‘Output.txt’ in the application path for display.

Input/Output File Naming Criteria –

    1. The User Linking Code begins with the Reading of the Inputs from the input file.
    2. The results of the code mentioned as per the algorithm must be written into the output file.
    3. The path of the input and the output file can be viewed in the Methodology screen of every coding program.
    4. The file paths are displayed in the text box on the left side of the Methodology screen.

Note: The naming of the input file and the output file must be same as the text displayed in the Methodology screen.

Input/Output file format ‘Input.txt’ file has three lines of inputs. The first line indicates the key text (exactly 16 hexadecimal characters). The second line of input gives the number of iterations (from 1 to 16). The third line of input gives the data text that has to be encrypted or decrypted.

Input file: Line 1: Key_text Line 2: No_of_iterations Line 3: Data_text

Example: abcdefabcdefabcd 10 NetSim

Output.txt ’ file has the following format: The number of lines present depends on the number of iterations chosen. The number of lines equals the number of iterations, plus one. The last line of input gives the data (encrypted data if encryption has been chosen, else the decrypted data if decryption has been chosen). The previous lines give the DES Key generated for encryption or decryption.

DesKeyGen1 #9; #9; DesKeyGen2 #9; #9; DesKeyGen3 #9; #9; . . . . . . . #9; #9; . . . . . . . #9; #9; . . . . . . . . . . . . . . #9; #9; DesKeyGen16 #9; #9; Encrypted/Decrypted Data

Example: For 10 iterations, key text: abcdefabcdefabcd, Data: NetSim

111011110111100101010111100010101111111000111111

010011110101011100111111101110010101110110101011

111011111001000111011101100011100111101000110111

000111111100101011101011111101110110101111110100

101110110111100110111010101100011000101111011011

101111000010111111001101110101111011011000010111

010100110111111000011101011111110010011111101100

010011011011110111110100001110001111100111001111

110100111110010100111100011111100010110111101101

110011001000111110110111101010101111100111011011

0DDF4D518007E5ED

Reading input file

FILE* fp = NULL; void main() #9; { char szKey[20]; char szStr[20000];

int nIter = 0;

//Assume that the NetSim is installed in C: drive and in the folder netsim. fp = fopen("c:\\netsim\\input.txt","r"); fgets(szStr,80,fp); strcpy(szKey,szStr); fgets(szStr,80,fp); nIter = atoi(szStr); fgets(szStr,20000,fp); fclose(fp); }

Writing Output file

//Assume that the NetSim is installed in C: drive and in folder netsim

fp = fopen("c:\\netsim\\output.txt","w"); #9; #9; . . . . . . . . . . . . #9; #9; fprintf(fp,"%s",szKeyGen[0]); #9; #9; . . . . . . . . . . . . #9; #9; fprintf(fp,"%s",szKeyGen[1]); #9; #9; . . . . . . . . . . . . #9; #9; fprintf(fp,"%s",szKeyGen[2]); #9; #9; . . . . . . . . . . . . #9; #9; fprintf(fp,"%s",szKeyGen[16]); #9; #9; fprintf(fp,"%s",szData); #9; #9; fclose(fp);

Decryption:

Input The data file has to be encrypted before decrypting. Before decrypting use, copy+paste to place the decrypt data in the specified text area. Using the copy button the result screen of the encryption output window is obtained as shown below. After this, click Link to decrypt.

Algorithm:

Global Arrays Used:

// The following are SBOX related tables. This is substitution table that is used to substitute the values to //the text corresponding to the binary values of the text got by the row index and the column index.

int g_Sbox1[4][16]= {

{14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7},

{0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8},

{4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0},

{15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13} #9; #9; };

int g_Sbox2[4][16]= {

{15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10},

{3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5},

{0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15},

{13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9}

};

int g_Sbox3[4][16]= {

{10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8},

{13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1},

{13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7},

{1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12}

};

int g_Sbox4[4][16]= {

{7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15},

{13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9},

{10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4},

{3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14}

};

int g_Sbox5[4][16]= {

{2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9},

{14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6},

{4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14},

{11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3}

};

int g_Sbox6[4][16]= {

{12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11},

{10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8},

{9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6},

{4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13}

};

int g_Sbox7[4][16]= {

{4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1},

{13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6},

{1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2},

{6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12}

};

int g_Sbox8[4][16]= {

{13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7},

{1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2},

{7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8},

{2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11}

};

// To generate 16 keys, you have to perform the shifting operation of the keys formed in each iteration #9; //Each index has the shifting values

int g_nShiftTable[16]={1,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1};

// All the tables here are obtained by some mathematical calculation (permutated table). //This is a table structure for making a 32-bit data value into a 48-bit data value that is used to perform the //XOR operation with the key value (corresponding to the iteration number).

int g_nEbitTable[48]= {

32, 1, 2, 3, 4, 5,


, 5, 6, 7, 8, 9,

8, 9, 10, 11, 12, 13,

13, 14, 15, 16, 17,

16, 17, 18, 19, 20, 21,

20, 21, 22, 23, 24, 25,

24, 25, 26, 27, 28, 29,

29, 30, 31, 32, 1

};

// This table is used to convert a 64-bit key value into a 56-bit key value.

int g_nPC1[56]= {

57, 49, 41, 33, 25, 17, 9,

1, 58, 50, 42, 34, 26, 18,

10, 2, 59, 51, 43, 35, 27,

19, 11, 3, 60, 52, 44, 36,

63, 55, 47, 39, 31, 23, 15,

7, 62, 54, 46,38,30,22,

14, 6, 61, 53, 45, 37, 29,

21, 13, 5, 28, 20, 12, 4

};

// This table is used to convert a 56-bit key value to a 48-bit key value.

int g_nPC2[48] = {

14, 17, 11, 24, 1, 5,

3, 28, 15, 6, 21, 10,

23, 19, 12, 4, 26, 8,

16, 7, 27, 20, 13, 2,

41, 52, 31, 37, 47, 55,

30, 40, 51, 45, 33, 48,

44, 49, 39, 56, 34, 53,

46, 42, 50, 36, 29, 32

};

// This is the initial transposition table for the plain text. It transposes every 64-bit of the plain text.

int g_nPC3[64]= {

58, 50, 42, 34, 26, 18, 10, 2,

60, 52, 44, 36, 28, 20, 12, 4,

&&62, 54, 46, 38, 30, 22, 14, 6,

&#@, 56, 48, 40, 32, 24, 16, 8,

ν, 49, 41, 33, 25, 17, 9, 1,

59, 51, 43, 35, 27, 19, 11, 3,

61, 53, 45, 37, 29, 21, 13, 5,

&&63, 55, 47, 39, 31, 23, 15, 7

};

// This is the transposition table for the text got after the SBOX iterations.

int g_nPC4[32] = {

16, 7, 20, 21,

29, 12, 28, 17,

1, 15, 23, 26,

&&5, 18, 31, 10,

&#, 8, 24, 14,

Τ, 27, 3, 9,

19, 13, 30, 6,

22, 11, 4, 2 };

// This is the final transposition process of the resultant text after various iterations

int g_nPC5 [64]= {

40, 8, 48, 16, 56, 24, 64, 32,

39, 7, 47, 15, 55, 23, 63, 31,

38, 6, 46, 14, 54, 22, 62, 30,

37, 5, 45, 13, 53, 21, 61, 29,

36, 4, 44, 12, 52, 20, 60, 28,

35, 3, 43, 11, 51, 19, 59, 27,

34, 2, 42, 10, 50, 18, 58, 26,

33, 1, 41, 9, 49, 17, 57, 25

};

Note for key generation and data encryption: The global variables given above are used for the transposition and substitution process. Use the corresponding database as given by the comments above the global variables, if required.

Key Generation Process: Generate 16 hexadecimal numbers, called "initial key".

    1. Reduce the 64-bit initial key to a 56-bit key using the transposition process.
    2. Split the 56-bit key into two halves, each of which is 28-bits long.
    3. Generate 16 sub-keys using left shift operation, each of which is 56-bits long.
    4. Reduce each of those 56-bit sub keys to a 48-bit sub key using the transposition process.

Data Encryption Process Take the first block of message text 'M' whose length is 64-bit (in binary). If it is not 64 bits long, make it 64-bit by adding padding bits.

5. Using the transposition process, rearrange the bit positions of 'M'.

6. Split the rearranged block into two halves, say L0 & R0, each of which is 32 bits long.

7. Change the R0 as the next L1.

8. To find next R1: Expand the R0 from 32-bits to 48-bits XOR expanded R0 and key 9; corresponding to this iteration.

9. Reduce that 48-bit output into a 32-bit using the substitution process. This is done by splitting the R1 into 8 groups with 6 bits each. Then, convert each 6 bit into 4 bits.

10. Reorder the bit positions of that 32-bit output using the transposition process.

11. Repeat steps 7 to 9 until the 16th iteration has been completed.

12. Swap the outputs that are obtained from the final iteration (i.e., the 16th iteration).

    • Reorder the bit positions of that 64-bit using the transposition process.
    • Convert the cipher text into character format.

Similarly, for Decryption Process, apply the same technique to the data to be encrypted to get back the original data (plain text).

Socket – TCP Send

Concept

1. A socket is a software entity that provides the basic building block for inter-process communications.

2. It also an interface between the application and the network.

3. Once the socket is configured, the application can pass data to the socket for network transmission and receive the data from the socket from the other host.

4. A socket communication can be connection oriented (TCP sockets) or connectionless (UDP sockets)

5. There is a receiver (TCP/UDP) server, which listens for the sender (TCP/UDP) clients to communicate. There can be two-way communication.

By selecting ‘sample program’, you can see the working of socket programming.

User inputs

1. #9; Select the option ‘Send’ to send data from the node and ‘Receive’ to receive data from other nodes.

2. #9; If you select ‘Send’, then enter the IP address of the destination node and enter the message to be sent.

3. You can select the protocol by which the socket communication can be made. i.e., the TCP protocol or the UDP protocol.

How to write you own code

9;

In the Sample mode, you have to select the required algorithm, enter the input data and click the button on the screen to view the results.

Whereas in User mode, you have to write your own program in the c/ C++, compile and link to NetSim software for validation. #9;

Click on the button to view the file path.

Note: The naming of the input and the output file must be same as the text displayed on the screen.

How to link your code

9; To link your code, click on the button to obtain the screen for retrieving the file path.

Click on browse button and find the path where you have your C/C++ file (.exe) stored. The .exe will be found in the "Debug" folder of your source code. Click OK after your .exe file is selected. Select the required Algorithm and enter the input data file. Click the button to view the output.

Copy the program given in "Code" below to the C++ complier and write your own code in the space written as " Write your code here".

Input/Output File Naming Criteria:

The User Linking Code begins with the Reading of the Inputs from the Input file.

The results of the code mentioned as per the Algorithm must be written into the Output file.

The Path of the input and the output file can be viewed in the Methodology screen of every coding program.

Pre-Conditions

You have to program your code such that it accepts the input from a specific TEXT (Extension ‘Txt’) file and write the output to a specific TEXT (Extension ‘Txt’) file in the specified path, which is given at the left side of the screen.

Note: Both the input and the output should be along the path where ‘NetSim Application’ is installed.

One needs to take care that the correct paths are mentioned for writing the input.txt and output.txt file. – These path can be got by clicking on the Button

Example: You would see a path like C:\Program Files\NetSim 2.0\input.txt Add additional "\" to make it C:\\Program Files\\NetSim 2.0\\input.txt Paste this path wherever input.txt is opened and read

Coding Pre Requisites:

There are certain program prerequisites for the creation of sockets in the Windows-based C complier. They are as follows:

1. The C complier must have winsock.h header file in its standard header file folder.

2. In order to use the commands of the winsock.h, there must be wsock32.lib library file present in the C complier. It must be linked to your application. For example, if you have a Visual Studio complier (6.0 version), the library file linkage must be made in the following way:

a. Click Project Menu in the workspace.

b. Select Setting in the pull-down menu.

c. Then click Link. The category in the pull down menu should be General.

d. Type wsock32.lib file in the Object/library modules text box area.

e. Click OK to confirm the changes in the workspace.

Pseudo Code

Store the server details in the "serv_addr"(sockaddr_in structure variable) and client details in the "cli_addr"(sockaddr_in structure variable).

serv_addr.sin_family = AF_INET;

serv_addr.sin_addr.s_addr = inet_addr (szIPAddress);

serv_addr.sin_port = htons (SERV_TCP_PORT);

cli_addr.sin_family = AF_INET;

cli_addr.sin_addr.s_addr = inet_addr (INADDR_ANY);

cli_addr.sin_port = htons (0);

If connect (sockfd, (struct sockaddr *) &serv_addr, sizeof (serv_addr)) is less than 0

Then return.

Open the file in read mode using fopen (argv [2],"r");

If fp (file pointer) is NULL

Then return.

Get the data from the file into a string szData using fgets (szData, 1000, fp).

Close the file.

Allocate memory for szBuffer using szBuffer = (char FAR *) malloc (1001);

Copy the data from the string szData to the string szBuffer

Find the size of szBuffer and store it in nBufferSize.

Call send command to send the data read from the file to the TCP Receiver

send (sockfd, szBuffer, nBufferSize+2, 1).

Code

Copy the code on to your C/C++ editor. Write your own code where you see "Write your code here". The pseudo code / algorithm is as given above

#include

#include

#include

#define SERV_UDP_PORT 6000

#define SERV_TCP_PORT 6000

void main(int argc,char * argv[])

{

FILE *fp=NULL;

SOCKET sockfd, newsockfd;

struct sockaddr_in cli_addr, serv_addr; // the structure is used by Windows Sockets to specify a local or remote endpoint address to which to connect a socket

WORD wVersionRequested; //specifies the highest version of Windows Sockets support that the caller can use

WSADATA wsaData; // is used to store Windows Sockets initialization information

//register struct hostent *hostptr;

int serv_len=0;

int FAR* addr_len = 0;

char FAR *szBuffer=NULL;

char szData [1001];

short int nLoop=0, nBufferSize=0;

int nErrorStatus=0;

if (argc<=4)

{

exit (0);

}

wVersionRequested = MAKEWORD (2, 2); // macro creates an unsigned 16-bit integer by concatenating two given unsigned character values.

nErrorStatus = WSAStartup (wVersionRequested, &wsaData);

if (nErrorStatus! = 0)

{

/* tell the user that we could not find a usable */

/* WinSock DLL. */

return;

}

/* Confirm that the WinSock DLL supports 2.2.*/

/* Note that if the DLL supports versions greater */

/* than 2.2 in addition to 2.2, it will still return */

/* 2.2 in wVersion since that is the version we */

/* requested. */

if (LOBYTE( wsaData.wVersion ) != 2 || \

HIBYTE( wsaData.wVersion ) != 2 )

{

/* Tell the user that we could not find a usable */

/* WinSock DLL. */

WSACleanup (); //function terminates use of the WS2_32.DLL.

return;

}

if(atoi(argv[3]) ==1 )

{

if((sockfd = socket(AF_INET,SOCK_DGRAM,0))<0)

{

return;

}

if (atoi(argv[4])==1){ /* UDP - Send */

serv_addr.sin_family = AF_INET;

serv_addr.sin_addr.s_addr = inet_addr(argv[1]);

serv_addr.sin_port = htons(SERV_UDP_PORT);

serv_len=sizeof(serv_addr);

cli_addr.sin_family = AF_INET;

cli_addr.sin_addr.s_addr = htonl(INADDR_ANY);

cli_addr.sin_port = htons(0);

if(bind(sockfd,(struct sockaddr *)&cli_addr, sizeof(cli_addr))<0)

{

return;

}

fp = fopen(argv[2],"r");

if(fp==NULL)

return;

fgets(szData,1000,fp);

fclose(fp);

szBuffer = (char FAR *)malloc(1001);

strcpy(szBuffer,szData);

nBufferSize = strlen(szBuffer);

sendto(sockfd,szBuffer,nBufferSize+2,0,(struct sockaddr *) &serv_addr,serv_len);

}

else if(atoi(argv[4])==2)

{ /* UDP - Receive */

serv_addr.sin_family = AF_INET;

serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);

serv_addr.sin_port = htons(SERV_UDP_PORT);

serv_len=sizeof(serv_addr);

if(bind(sockfd,(struct sockaddr *)&serv_addr, sizeof (serv_addr))<0)

{

return;

}

for(;;)

{

recvfrom(sockfd,szData,sizeof(szData),0,(struct sockaddr *) &serv_addr, &serv_len);

fp = fopen(argv[2],"w");

if(fp==NULL)

{

return;

}

fputs(szData,fp);

fclose(fp);

break;

}

}

else

{

return;

}

closesocket(sockfd);

}

else if(atoi(argv[3])==2)

{

if((sockfd = socket(AF_INET,SOCK_STREAM,0))<0)

{

return;

}

serv_addr.sin_family = AF_INET;

serv_addr.sin_port = htons(SERV_TCP_PORT);

if (atoi(argv[4])==1)

{ /* TCP - Send */

//

Write your code here

}

else if (atoi(argv[4])==2)

{ /* TCP - Receive */

serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);;

if(bind(sockfd,(struct sockaddr *)&serv_addr, sizeof(serv_addr))<0)

{

return;

}

listen(sockfd,1);

for(;;)

{

serv_len=sizeof(cli_addr);

newsockfd = accept(sockfd,(struct sockaddr *)&cli_addr,&serv_len);

if(newsockfd<0)

{

return;

}

recv(newsockfd,szData,sizeof(szData),2);

fp = fopen(argv[2],"w");

if(fp==NULL)

return;

fputs(szData,fp);

fclose(fp);

closesocket(newsockfd);

if(newsockfd>0)

break;

}

}

else

{

return;

}

closesocket(sockfd);

}

else

{

}

return;

}

No comments: