Upload
dr-praveen-jain
View
91
Download
1
Embed Size (px)
Citation preview
1
Experiment Manual
2
The information contained in this document represents the current view of TETCOS on the
issues discussed as of the date of publication. Because TETCOS must respond to changing
market conditions, it should not be interpreted to be a commitment on the part of TETCOS,
and TETCOS cannot guarantee the accuracy of any information presented after the date of
publication.
This manual is for informational purposes only. TETCOS MAKES NO WARRANTIES,
EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS
DOCUMENT.
Warning! DO NOT COPY
Copyright in the whole and every part of this manual belongs to TETCOS and may not be
used, sold, transferred, copied or reproduced in whole or in part in any manner or in any
media to any person, without the prior written consent of TETCOS. If you use this manual
you do so at your own risk and on the understanding that TETCOS shall not be liable for any
loss or damage of any kind.
TETCOS may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from TETCOS, the furnishing of this document does not give you
any license to these patents, trademarks, copyrights, or other intellectual property. Unless
otherwise noted, the example companies, organizations, products, domain names, e-mail
addresses, logos, people, places, and events depicted herein are fictitious, and no association
with any real company, organization, product, domain name, email address, logo, person,
place, or event is intended or should be inferred.
Rev 9.1 (V), August 2016 , TETCOS. All rights reserved.
All trademarks are property of their respective owner.
Contact us at –
TETCOS
214, 39th A Cross, 7th Main, 5th Block Jayanagar,
Bangalore - 560 041, Karnataka, INDIA. Phone: +91 80 26630624
E-Mail: [email protected]
Visit: www.tetcos.com
3
NetSim Experiment Manual
Contents
1. Hamming Code ..................................................................................... 4
2. Transmission Flow Control .................................................................... 9
3. Sliding Window Protocol ..................................................................... 15
4. High Level Data Link Control ............................................................... 31
5. Client – Server Model .......................................................................... 45
6. Socket Program for Talk ...................................................................... 53
7. CSMA/CA and CSMA/CD ..................................................................... 59
8. Network Topology –Star, Bus, Ring ..................................................... 67
9. Distance Vector Routing ...................................................................... 75
10. Link State Routing ............................................................................... 82
11. Congestion Control Algorithm ............................................................. 89
12. Encryption and Decryption ................................................................ 100
Appendix 1: Programming exercise -How to practice without NetSim ........ 109
Appendix 2: Creating .exe file using Dev C++ .............................................. 113
4
1. Hamming Code
1.1 Objective:
Implementation of Error Detection/Error Correction Techniques
1.2 Theory:
Hamming code is for Single Bit Error Detection and Correction. It is based on Parity (Even /
Odd Parity).
It allows any single bit error to be detected and corrected. It involves adding one or four
check bits (depending on the formula) to the data for error detection as well as error
correction. These bits are called Check Bits. In order to find the number of check bits
introduced in the message bits, there is a general formula.
Formula:
For a message of size m bits and r check bits, then the condition (m + r + 1) < = 2 r should be
valid.
Example:
Consider the message size (m) of 4 bits and we will find out the number of check bits
according to the formula,
When r = 3 we have,
4 + 3 + 1 = 8 and 2 3 is 8 and so the number of Check Bits to be introduced is 3.
1.3 Algorithm:
Read the contents of the input file i.e. the input data, type of parity and the error data from the
„Input.txt‟ and store it in variables like the above method.
1. Get the length of the input data and calculate the number of Check Bits to be
introduced according to the condition (m + r + 1) <= 2r. Where m is length of the
original data and r is the number of check bits to be introduced in the string.
2. If the passed flag (type of parity) is 2, then it is Even parity, else it is Odd parity.
5
3. Place the Check Bits at the appropriate position according to the principle explained
above (Calculation and Placement of Check Bits in Hamming Code) for the Input data
and for the Error data.
4. Compare the Check Bits values of the Original Input Data and the Error Data values.
Keep a note of the Check Bit Position where the value differs.
5. Add all the position of the Check Bits where the values differ. The resultant value
gives the position of the error bit in the Error Data of length ( m + r ) i.e. the total
length which includes the length of the Input Data Bits and the Check Bits.
1.4 Procedure:
In NetSim, Select “Programming Error Correcting Code Hamming Code”.
Step 1:
In the left panel, select the Mode as Sample. Select Parity as “Odd”, input data and error
position and click Run.
So presently NetSim will run Hamming code already present in the software and will display
the result graphically
Select the
Mode
Select the Parity
6
Result:
After you click RUN button you can see the Hamming string, Original data and Error data in
binary format as shown in the following screen shots
Output
Enter the Data
Select the Error Position
Click run to execute
Click here to view the Concept,
Algorithm, Pseudo code and Flow
chart
7
Step 2:
Open Dev C++ or any GNU C compiler based IDK and copy the code that is opened when
the Interface Source Code link is clicked.
The user needs to edit this code at the following location.
int fnHamming()
{
// Write your own code here
return iErrorPosition;
}// End of Function fnhammingErrorPosition.
So the user needs to add the user code, create exe and attach it with NetSim to run.
The User code which is to be added is given below
int fnHamming()
{
/////* User code part start */
iMessageLength = strlen(szOriginalString); // Get the Input Length
iCheckCount = fnGetCheckbitscount(iMessageLength);
// Allocate the Required Memory for Original Hamming String
szHammingOriginal = malloc(iMessageLength + iCheckCount + 1);
// Position the Check Bits into the Original Hamming String
szHammingOriginal = fnPositionCheckBits(iMessageLength, iCheckCount,
iParitytype, szOriginalString, 'O');
// Allocate the Required Memory for Error Hamming String
szHammingError = malloc(iMessageLength + iCheckCount + 1);
// Position the Check Bits into the Error Hamming String
szHammingError = fnPositionCheckBits(iMessageLength, iCheckCount,
iParitytype, szErrorString, 'E');
// Get the error position
iErrorPosition = fnErrorPosition(szHammingOriginal, szHammingError, strlen(
szHammingOriginal), iCheckCount);
/////* User code part end */
return iErrorPosition;
}// End of Function fnhammingErrorPosition.
Create .exe file (Appendix 2: Creating .exe file using Dev C++)
In the left panel, select the Mode as User. Select the .exe file created above.
Select Parity as “Odd”, input data and error position and click Run.
So presently NetSim will run Hamming code which is written by the user and will display the
result graphically.
In case of any error, “ERROR IN USER CODE” message will be displayed.
Note- How to practice this experiment without using NetSim
8
Users who do not have a licensed version of NetSim in their PC's, can practice as explained
below.
First, run the exercise in sample mode. The user would see that an Input.txt file is created in
Win OS temp folder (this can be reached by typing %temp%/NetSim in Windows run
window). This input file should be read by the user code and it should generate an Output.txt.
This Output.txt file is read by NetSim and shown graphically to the user.
User can follow the steps provided in Appendix 1: Programming exercise - How to practice
without NetSim.
Given below are sample Input.txt and Output.txt files for this experiment for users to verify
& validate their code
Input.txt file contents
Parity=Odd
Data=Netsim
Error_Position=1
Data_Bits_Original=010011100110010101110100011100110110100101101101
Data_Bits_Error=010011100110010101110100011100110110100101101100
Output.txt file contents
6
3>5>7>9>11>13>15>17>19>21>23>25>27>29>31>33>35>37>39>41>43>45>47>49>51>53>0>1>
3>6>7>10>11>14>15>18>19>22>23>26>27>30>31>34>35>38>39>42>43>46>47>50>51>54>1>0
>
5>6>7>12>13>14>15>20>21>22>23>28>29>30>31>36>37>38>39>44>45>46>47>52>53>54>1>0
>
9>10>11>12>13>14>15>24>25>26>27>28>29>30>31>40>41>42>43>44>45>46>47>1>0>
17>18>19>20>21>22>23>24>25>26>27>28>29>30>31>48>49>50>51>52>53>54>0>1>
33>34>35>36>37>38>39>40>41>42>43>44>45>46>47>48>49>50>51>52>53>54>0>1>
3>5>7>9>11>13>15>17>19>21>23>25>27>29>31>33>35>37>39>41>43>45>47>49>51>53>1>0>
3>6>7>10>11>14>15>18>19>22>23>26>27>30>31>34>35>38>39>42>43>46>47>50>51>54>0>1
>
5>6>7>12>13>14>15>20>21>22>23>28>29>30>31>36>37>38>39>44>45>46>47>52>53>54>1>0
>
9>10>11>12>13>14>15>24>25>26>27>28>29>30>31>40>41>42>43>44>45>46>47>1>0>
17>18>19>20>21>22>23>24>25>26>27>28>29>30>31>48>49>50>51>52>53>54>0>1>
33>34>35>36>37>38>39>40>41>42>43>44>45>46>47>48>49>50>51>52>53>54>0>1>
1>2>3>
9
2. Transmission Flow Control
2.1 Objective
Implementation of Stop and Wait Protocol and sliding window
2.2 Theory
Stop and Wait is a reliable transmission flow control protocol. This protocol works only in
Connection Oriented (Point to Point) Transmission. The Source node has window size of
ONE. After transmission of a frame the transmitting (Source) node waits for an
Acknowledgement from the destination node. If the transmitted frame reaches the destination
without error, the destination transmits a positive acknowledgement. If the transmitted frame
reaches the Destination with error, the receiver destination does not transmit an
acknowledgement. If the transmitter receives a positive acknowledgement it transmits the
next frame if any. Else if its acknowledgement receive timer expires, it retransmits the same
frame.
2.3 Algorithm
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 form packet and pass data file path, which is got by parsing
the file Input.txt.
3. Repeat the loop until the transmitting list (transmitting node) becomes empty
10
a. Get the first frame of the transmitting list and transmit to destination.
b. Call the Error Check function, pass the frame got and the variable err value as
parameters. The returned value is stored in a local variable iret.
c. If the value of the iret is 0 (No Error Condition),
i. Form the positive acknowledgement and place it in the transmission
list of Node2.
ii. To form positive acknowledgements create a new frame and set the
data field as "POS". Then set this frame as the first frame of Node2.
iii. Get the acknowledgement value from the receiving node‟s
transmission list.
1. If the acknowledgement has error or the timer has expired
a. Resend the same frame
2. If the acknowledgement has no error nor the timer has expired
b. Delete the first frame from the transmission list of
Node1.
c. Delete the acknowledgement frame from Node2
transmission list.
d. If the value of the iret is 1 (Error Condition),
i. Resend the first frame of the transmitting list to destination.
2.4 Procedure
In NetSim, Select “Programming Transmission Flow Control”.
The scenario will be obtained as shown below. Follow the steps.
Step 1:
In the left panel, select the Mode as Sample. Select the algorithm as Stop and Wait. Create a
small text file (within 15000 bytes) and set it as input. Also set the Bit error rate (BER) and
click Run.
So presently NetSim will run Stop and Wait code already present in the software and will
display the result graphically
11
Result:
Select the Mode
Select the Algorithm
Choose the required data
Choose the bit error rate
Click here to view the Concept,
Algorithm, Pseudo code and Flow
chart
Output Table
Click run to execute
12
2.5 Inference
Due to increase in the error rate, no of errored packets also increase. If errored packets
increase no of retransmitted packets also increase.
Step 2:
For user to write their own C Code in NetSim and check the result, click on Interface Source
Code (present in Help in the left pane).
Open Dev C++ or any GNU C compiler based IDK and copy the code from the Interface
Source Code.
The user needs to edit the Interface Source Code at the following location.
void stopandwait(int errrate)
{
// Write your own code here
}
So the user needs to add the user code, create exe and attach it with NetSim to run.
The User code which is to be added is given below
void stopandwait(int errrate)
{
/////* User code part start */
// Repeat the loop until transmission list of the transmitting
// node becomes empty
while(nodelist_sw->txframe != NULL)
{
// Get the current transmitting frame reference
transframe_sw = ret_txframe_SW ();
// Write the content into the output file. Data Value is written
//into the file
fprintf(fp_sw,"DT>%d>%s>%s>\n",transframe_sw->iframe,transframe_sw-
>szsrcaddr,transframe_sw->szdestaddr);
/*
Call the default function defined in the header file main1.h
Store the return value to the local variable iret_sw.
The Passed arguments
1. errrate -- This is the variable passed to the function (got from
the function call of the retErrorrate)
2. transframe_sw -- This is Eth_frame_sw reference that has the
Transmitting frame got from the function call ret_txframe_SW
*/
iret_sw=intro_error_SW(errrate,transframe_sw);
13
// Write the content into the output file. Error value is written into
//the file
fprintf(fp_sw,"EV>%d>%s>%s>\n",iret_sw,transframe_sw-
>szsrcaddr,transframe_sw->szdestaddr);
// Check if the frame is Positive or Negative
if(iret_sw == 0)// Positive acknowledgment in the network
{
// Form the Ack frame according to the iret_sw value
form_ack_SW (transframe_sw,1);// Positive Acknowledgement
// Call the ret_ackframe_sw function and get the acknowledgement
frame
//reference from the tranmitting list of the receiving node
ackframe_sw=ret_ackframe_sw ();
// Write the content into the file. Positive Ack value
fprintf(fp_sw,"ACK>POS>%s>%s>\n",ackframe_sw->szsrcaddr,ackframe_sw-
>szdestaddr);
// Acknowledgement frame is made so delete the transmitted frame
from
//the transmitting list of the source node
del_frame_SW(transframe_sw ->ipack,transframe_sw ->iframe);
// User defined function call to delete the Acknowledgement frame
del_ackframe_sw ();
}
}
/////* User code part end */
}
Create .exe file (Appendix 2: Creating .exe file using Dev C++)
In the left panel, select the Mode as User. Select the .exe file created above.
Select the algorithm as Stop and Wait. Create a small text file (within 15000 bytes) and set it
as input. Also set the Bit error rate (BER) and click Run.
So presently NetSim will run Stop and Wait code which is written by the user and will
display the result graphically.
In case of any error, “ERROR IN USER CODE” message will be displayed.
Note- How to practice this experiment without using NetSim:
Users who do not have a licensed version of NetSim in their PC's, can practice as explained
below.
First, run the exercise in sample mode. The user would see that an Input.txt file is created in
Win OS temp folder (this can be reached by typing %temp%/NetSim in Windows run
window). This input file should be read by the user code and it should generate an Output.txt.
This Output.txt file is read by NetSim and shown graphically to the user.
14
User can follow the steps provided in Appendix 1: Programming exercise - How to practice
without NetSim.
Given below are sample Input.txt and Output.txt files for this experiment for users to verify
& validate their code. The Output.txt file will vary based on the Data_file. In this case, the
size of Data_File file is 11,305 bytes.
Input.txt file contents
Algorithm=Stop_and_Wait
Data_File=C:\Users\Tetcos\Desktop\ data.txt>
BER=0
*Note- Create any file of size <15000 Byte. Type the location of the file in Data_File.
Output.txt file contents
DT>1>node1>node2>
EV>0>node1>node2>
ACK>POS>node2>node1>
DT>2>node1>node2>
EV>0>node1>node2>
ACK>POS>node2>node1>
DT>3>node1>node2>
EV>0>node1>node2>
ACK>POS>node2>node1>
DT>4>node1>node2>
EV>0>node1>node2>
ACK>POS>node2>node1>
DT>5>node1>node2>
EV>0>node1>node2>
ACK>POS>node2>node1>
DT>6>node1>node2>
EV>0>node1>node2>
ACK>POS>node2>node1>
DT>7>node1>node2>
EV>0>node1>node2>
ACK>POS>node2>node1>
DT>8>node1>node2>
EV>0>node1>node2>
ACK>POS>node2>node1>
*Note- Output.txt content will vary depending on the file size
15
3. Sliding Window Protocol
3.1 Objective
Implementation and study of Go Back-N and Selective Repeat protocols
3.2 Part A – Go Back-N
3.2.1 Theory
Go Back N is a connection oriented transmission. The sender transmits the frames
continuously. Each frame in the buffer has a sequence number starting from 1 and increasing
up to the window size. The sender 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.
3.2.2 Operations
A station may send multiple frames as allowed by the window size.
Receiver sends an ACK i if frame i has an error. After that, the receiver discards all
incoming frames until the frame with error is correctly retransmitted.
If sender receives an ACK i it will retransmit frame i and all packets i+1, i+2,... which
have been sent, but not been acknowledged
3.2.3 Algorithm
1. The source node transmits the frames continuously.
2. Each frame in the buffer has a sequence number starting from 1 and increasing up
to the window size.
3. 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.
4. The size of the window depends on the protocol designer.
5. For the first frame, the receiving node forms a positive acknowledgement if the
frame is received without error.
16
6. If subsequent frames are received without error (up to window size) cumulative
positive acknowledgement is formed.
7. If the subsequent frame is received with error, the cumulative acknowledgment
error-free frames are transmitted. 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.
8. The source node retransmits all frames of window from the first error frame.
9. 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.
10. If the acknowledgment is transmitted with error, all the frames of window at
source are retransmitted, and window doesn‟t slide.
11. This concept of repeating the transmission from the first error frame in the
window is called as GO BACK-N transmission flow control protocol.
3.2.4 Procedure
In NetSim, Select “Programming Sliding Window Protocol”.
The scenario will be obtained as shown below. Follow the steps.
Step 1:
In the left panel, select the Mode as Sample. Select the algorithm as Go Back N. Create a
small text file (within 100 Kbytes) and set it as input. Also set the Bit error rate (BER),
Sequence number and click Run.
So presently NetSim will run Go Back N code already present in the software and will
display the result graphically
17
Step 2:
Select the Mode
Select Go Back N
Choose the input
data file
Choose the Bit
Error Rate
Choose the
Sequence Number
Click run to execute
Click here to view the Concept,
Algorithm, Pseudo code and Flow
chart
18
Result:
After you click RUN button you can see the output as shown in the following screen shots
Step 3:
Open Dev C++ or any GNU C compiler based IDK and copy the code that is opened when
the Interface Source Code link is clicked.
The user needs to edit this code at the following location.
void fnGoBackN()
{
// Write your own code here
}
So the user needs to add the user code, create exe and attach it with NetSim to run.
The User code which is to be added is given below
void fnGoBackN() { /////* User code part start */ double nFileSize=0; // stores file size of a input file long nPacketSize = 1500; // constant packet size 1500 int nNoofPackets; int i; int packet_num=1,window_start=1,count=0; int flag=0; int nErrorflag; int packets_to_send;
Output Table
19
nFileSize = get_file_size(); // calculate the total no of packets. The ceil function rounds up to nearest integer. // ceil return double so typecast to int. nNoofPackets = (int)ceil(nFileSize / nPacketSize); while(nNoofPackets) { packets_to_send = min(nNoofPackets,nWindowSize); write_output(1,packets_to_send,0); flag=0; packet_num=window_start; count=0; for(i=0;i<packets_to_send;i++) { nErrorflag = g_fnDecideError_GBN(nErrorrate,nPacketSize); write_output(2,packet_num,nErrorflag); // Packet writing packet_num++; if(!nErrorflag && !flag) { window_start++; count++; } if(nErrorflag) flag=1; } write_output(3,0,0); // Ack writing nNoofPackets = nNoofPackets- count; } /////* User code part end */ }
Creating a .exe file is explained in the end of this manual marked “Appendix 2: Creating .exe
file using Dev C++”
In the left panel, select the Mode as User. Select the .exe file created above.
Select the algorithm as Go Back N. Create a small text file (within 100 Kbytes) and set it as
input. Also set the Bit error rate (BER), Sequence number and click Run.
So presently NetSim will run Go Back N code which is written by the user and will display
the result graphically.
In case of any error, “ERROR IN USER CODE” message will be displayed.
Note- How to practice this experiment without using NetSim
Users who do not have a licensed version of NetSim in their PC's, can practice as explained
below.
20
First, run the exercise in sample mode. The user would see that an Input.txt file is created in
Win OS temp folder (this can be reached by typing %temp%/NetSim in Windows run
window).
This input file should be read by the user code and it should generate an Output.txt. This
Output.txt file is read by NetSim and shown graphically to the user.
User can follow the steps provided in Appendix 1: Programming exercise - How to practice
without NetSim.
Given below are sample Input.txt and Output.txt files for this experiment for users to verify
& validate their code
Input.txt file contents
Algorithm=Go_Back_N
Data_File=C:\Users\Tetcos\Desktop\data.txt>
Bit_Error_Rate=5
Sequence_Number=3
Window_Size=7
*Note- Create any file of size <100 KByte. Type the location of the file in Data_File.
Output.txt file contents
CNT>7>FRAMES>TRANSMIT>
DT>1>node1>node2>
EV>1>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>node1>node2>
CNT>7>FRAMES>TRANSMIT>
DT>1>node1>node2>
EV>0>node1>node2>
DT>2>node1>node2>
21
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>node1>node2>
CNT>1>FRAMES>TRANSMIT>
DT>8>node1>node2>
EV>0>node1>node2>
ACK>POS>node1>node2>
*Note- Output.txt content will vary depending on the file size
22
3.3 Selective Repeat
3.3.1 Theory:
Selective repeat is Similar to Go Back N. However, the sender only retransmits frames for
which an ACK is received.
Advantage over Go Back N:
Fewer retransmissions.
Disadvantages:
More complexity at sender and receiver
Receiver may receive frames out of sequence
3.3.2 Algorithm:
1. The source node transmits the frames continuously.
2. Each frame in the buffer has a sequence number starting from 1 and increasing up
to the window size.
3. 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.
4. 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.
5. The size of the window depends according to the protocol designer.
6. 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)
7. If all the frames are received without error, a cumulative positive
acknowledgement is sent.
8. If there is an error in frame 3, an acknowledgement for the frame 2 is sent and
then only Frame 3 is retransmitted. Now the window slides to get the next frames
to the window.
9. 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)
23
10. If all the frames transmitted are errorless the next transmission is carried out for
the new window.
11. This concept of repeating the transmission for the error frames only is called
Selective Repeat transmission flow control protocol.
3.3.3 Procedure:
In NetSim, Select “Programming Sliding Window Protocol”.
The scenario will be obtained as shown below. Follow the steps.
Step 1:
In the left panel, select the Mode as Sample. Select the algorithm as Selective Repeat. Create
a small text file (within 100 Kbytes) and set it as input. Also set the Bit error rate (BER),
Sequence number and click Run.
So presently NetSim will run Selective Repeat code already present in the software and will
display the result graphically
Select the Mode
Select the algorithm
24
Result:
After you click RUN button you can see the output as shown in the following screen shots
Choose the input
data file
Choose the Bit
Error Rate
Choose the
Sequence Number
Click run to execute
Output Table
Click here to view the Concept,
Algorithm, Pseudo code and Flow
chart
25
Step 2:
Open Dev C++ or any GNU C compiler based IDK and copy the code that is opened when
the Interface Source Code link is clicked.
The user needs to edit this code at the following location.
void selRep(char* szstr,char* error_rate, char* szPasWindowSize)
{
// Write your own code here
}
So the user needs to add the user code, create exe and attach it with NetSim to run.
The User code which is to be added is given below
void selRep(char* szstr,char* error_rate, char* szPasWindowSize) { /////* User code part start */ int nFileSize=0; // stores file size of a input file struct stat fInfo; // to get file information long int nPacketSize = 1500; // constant packet size 1500 int nWindowSize; // stores window size int nPasWindowSize; int nNoofPackets=0; // stores no of packets int nNoErrorPacket=0; int nNoofPacketsSent =0; // stores no of packets sent int nPacketCount=0; char *pszPath = NULL; int nLoop=0; // looping variable int nLoop1=0; int nErrorBit=0; // To store 0/1 0---- no error 1----- error int nErrorPacketIndex[100]={0}; // To store 0/1 0---- no error 1----- error int nErrorPacketValue[100]={0}; // To store 0/1 0---- no error 1----- error int nErrorFlag=0; // To indicate error is there in the last packet int nErrorPacketCount=0; // Stores error packets count FILE *fpTemp=NULL; // file pointer to write Temp.txt int nErrorrate=0; // Stores Error rate int nErrorWindowSize=0; int nalreadyError=0; nPasWindowSize = atoi(szPasWindowSize); nWindowSize = nPasWindowSize; nErrorrate = atoi(error_rate); // converts error rate from strings to fpTemp = fopen(szOutput_path_SR,"w");// open output.txt file with write mode fpTemp = fopen(szOutput_path_SR,"a+");// open output.txt file with append mode
26
stat(szstr,&fInfo); nFileSize = fInfo.st_size; // find the file size of a given input file printf("%d\n",nFileSize); nNoofPackets = nFileSize / nPacketSize; // calculate the tital no of packets if((nFileSize%nPacketSize)>0) // in the given file nNoofPackets = nNoofPackets + 1; while (nNoErrorPacket<nNoofPackets) // If no of packets successfully sent packet is less than { // total no of packets nLoop1=0; nErrorFlag = 0; nWindowSize =nPasWindowSize; for (nLoop = 0; nLoop<nWindowSize; nLoop++) // if any error in the last window { if(nErrorPacketIndex[nLoop] == 1) // set the error flag as 1 { nErrorFlag = 1; break; } } if(nErrorFlag == 0) nalreadyError = 0; else if((nErrorFlag ==1) && (nalreadyError == 1)) nErrorPacketCount = 0; if(nErrorFlag ==0) // re initialise the values { for(nLoop=0;nLoop<nWindowSize;nLoop++) { nErrorPacketIndex[nLoop]=0; nErrorPacketValue[nLoop]=0; } nErrorPacketCount = 0; } if(nErrorFlag == 0) { if((nNoofPackets - nNoErrorPacket) < nWindowSize) // If no of packets - no of packets sent nWindowSize = nNoofPackets - nNoErrorPacket; // is less than the window size // make the difference as window size fprintf(fpTemp,"CNT>%d>FRAMES>TRANSMIT>\n",nWindowSize); for(nLoop = 0; nLoop<nWindowSize ; nLoop++) // up to the window size { nErrorBit = g_fnDecideError_SR(nErrorrate,nPacketSize); // call function to decide error if(nErrorBit == 0) // if there is no error { nNoofPacketsSent++; // increment nNoErrorPacket++;
27
nPacketCount++; fprintf(fpTemp,"DT>%d>node1>node2>\n",nPacketCount); fprintf(fpTemp,"EV>%d>node1>node2>\n",nErrorBit); nErrorPacketIndex[nLoop]=0; nErrorPacketValue[nLoop]=nPacketCount; } else if(nErrorBit == 1) { nNoofPacketsSent++; nPacketCount++; fprintf(fpTemp,"DT>%d>node1>node2>\n",nPacketCount); fprintf(fpTemp,"EV>%d>node1>node2>\n",nErrorBit); nErrorPacketIndex[nLoop] = 1; nErrorPacketValue[nLoop]=nPacketCount; } } fprintf(fpTemp,"ACK>POS>node1>node2>\n"); } else if(nErrorFlag == 1) { nalreadyError = 1; if((nNoofPackets - nNoErrorPacket-nErrorPacketCount) < nWindowSize) nErrorWindowSize = nNoofPackets - nNoErrorPacket-nErrorPacketCount; else nErrorWindowSize = nWindowSize; fprintf(fpTemp,"CNT>%d>FRAMES>TRANSMIT>\n",nErrorWindowSize); for(nLoop=0; nLoop<nWindowSize; nLoop++) // searching the whole window for errors { if(nErrorPacketIndex[nLoop] == 1) { nErrorPacketCount++; nErrorBit = g_fnDecideError_SR(nErrorrate,nPacketSize); if(nErrorBit == 0) { nNoErrorPacket++; //nPacketCount++; fprintf(fpTemp,"DT>%d>node1>node2>\n",nErrorPacketValue[nLoop]); fprintf(fpTemp,"EV>%d>node1>node2>\n",nErrorBit); nErrorPacketIndex[nLoop1]=0; nErrorPacketValue[nLoop1] = nErrorPacketValue[nLoop]; } else if(nErrorBit == 1) { fprintf(fpTemp,"DT>%d>node1>node2>\n",nErrorPacketValue[nLoop]); fprintf(fpTemp,"EV>%d>node1>node2>\n",nErrorBit);
28
//nErrorPacketIndex[nLoop] = 1; //nErrorPacketValue[nLoop]=nNoofPacketsSent; nErrorPacketIndex[nLoop1] = 1; nErrorPacketValue[nLoop1] = nErrorPacketValue[nLoop]; //nLoop1++; } nLoop1++; } } if((nNoofPackets - nNoErrorPacket) < nWindowSize) // If no of packets - no of packets sent nWindowSize = nNoofPackets - nNoErrorPacket;//-nErrorPacketCount ; // is less than the window size // make the difference as window size else nWindowSize = nWindowSize - nErrorPacketCount; //fprintf(fpTemp,"CNT>%d>FRAMES>TRANSMIT>\n",nWindowSize); for(nLoop=0;nLoop<nWindowSize; nLoop++) { nErrorBit = g_fnDecideError_SR(nErrorrate,nPacketSize); if(nErrorBit == 0) { nNoofPacketsSent++; nNoErrorPacket++; nPacketCount++; fprintf(fpTemp,"DT>%d>node1>node2>\n",nPacketCount); fprintf(fpTemp,"EV>%d>node1>node2>\n",nErrorBit); nErrorPacketIndex[nLoop1]=0; nErrorPacketValue[nLoop1]=nPacketCount; } else if(nErrorBit == 1) { nNoofPacketsSent++; nPacketCount++; fprintf(fpTemp,"DT>%d>node1>node2>\n",nPacketCount); fprintf(fpTemp,"EV>%d>node1>node2>\n",nErrorBit); nErrorPacketIndex[nLoop1] = 1; nErrorPacketValue[nLoop1]=nPacketCount; } nLoop1++; } fprintf(fpTemp,"ACK>POS>node1>node2>\n"); } } fclose(fpTemp); /////* User code part end */ }
Creating a .exe file is explained in the end of this manual marked “Appendix 2: Creating .exe
file using Dev C++”
29
In the left panel, select the Mode as User. Select the .exe file created above.
Select the algorithm as Selective Repeat. Create a small text file (within 100 Kbytes) and set
it as input. Also set the Bit error rate (BER), Sequence number and click Run.
So presently NetSim will run Selective Repeat code which is written by the user and will
display the result graphically.
In case of any error, “ERROR IN USER CODE” message will be displayed.
Note- How to practice this experiment without using NetSim
Users who do not have a licensed version of NetSim in their PC's, can practice as explained
below.
First, run the exercise in sample mode. The user would see that an Input.txt file is created in
Win OS temp folder (this can be reached by typing %temp%/NetSim in Windows run
window). This input file should be read by the user code and it should generate an Output.txt.
This Output.txt file is read by NetSim and shown graphically to the user.
User can follow the steps provided in Appendix 1: Programming exercise - How to practice
without NetSim.
Given below are sample Input.txt and Output.txt files for this experiment for users to verify
& validate their code
Input.txt file contents
Algorithm=Selective_Repeat
Data_File=C:\Users\Tetcos\Desktop\data.txt>
Bit_Error_Rate=5
Sequence_Number=3
Window_Size=4
*Note- Create any file of size <100 KByte. Type the location of the file in Data_File.
Output.txt file contents
CNT>4>FRAMES>TRANSMIT>
DT>1>node1>node2>
EV>0>node1>node2>
DT>2>node1>node2>
30
EV>0>node1>node2>
DT>3>node1>node2>
EV>0>node1>node2>
DT>4>node1>node2>
EV>1>node1>node2>
ACK>POS>node1>node2>
CNT>4>FRAMES>TRANSMIT>
DT>4>node1>node2>
EV>0>node1>node2>
DT>5>node1>node2>
EV>0>node1>node2>
DT>6>node1>node2>
EV>1>node1>node2>
DT>7>node1>node2>
EV>0>node1>node2>
ACK>POS>node1>node2>
CNT>2>FRAMES>TRANSMIT>
DT>6>node1>node2>
EV>0>node1>node2>
DT>8>node1>node2>
EV>0>node1>node2>
ACK>POS>node1>node2>
*Note- Output.txt content will vary depending on the file size
31
4. High Level Data Link Control
4.1 Objective:
Implementation of High Level Data Link Control
4.2 Part A - Bit Stuffing
4.2.1 Theory:
When data is transmitted, the transmitter should distinguish between the start and the end of
the data. This is done to ensure that the receiving node reads the data completely. This is
accomplished by appending a unique pattern of bit stream before and after the data. Care
should be taken to ensure that this unique pattern does not occur in the data itself. If the
pattern appears in the data then the data is broken. The process of appending a unique pattern
and breaking the pattern is known as framing.
Bit Stuffing is one of the framing methods, in which each frame begins and ends with a
special bit pattern „0111110‟, called a flag byte.
Whenever the sender‟s data link layer encounters six consecutive 1‟s in the data, it
automatically stuffs a 0 bit into the outgoing bit stream to break the pattern.
4.2.2 Algorithm:
1. Get the Value of Destination Address, Source Address, Data, CRC Polynomial and
Error Status by reading Input.txt.
2. Call the function fnASCII_to_Binary () to get the Binary Values for each
characters in the Data field.
3. Call the function fnBitStuffing () to do the bit stuffing process.
4. Calculate the checksum by calling the function fnCheckSum_Calculation.
5. Initialize nLoop1, nCount and nIndex to zero.
6. Combine the Destination Address, Source Address and Binary Values in single
character array.
32
7. Loop through all the bits
Check nLoop_Length >= 0 && nLoop_Length < 8
Check pszBits [nLoop_Length] == 1
Increment nCount by 1
Stuffed Destination Address [nIndex] = „1‟
Check nCount == 5
Increment nIndex by 1
Stuffed Destination Address [nIndex] = „0‟
nCount = 0
Increment nIndex by 1
Else
nCount = 0
Stuffed Destination Address [nIndex] = „0‟
Increment nIndex by 1
Check nLoop_Length == 7
Stuffed Destination Address [nIndex] = „\0‟
nIndex = 0
8. Similarly repeat step6 for the Source Address and Binary Values for the stuffing
process.
9. Call the function fnDestuffing () to do the destuffing process.
10. Initialize nLoop1, nCount and nIndex to zero.
11. Loop through all the bits
Check pszBits [nLoop_Length] == 1
Increment nCount by 1
Check nCount == 5
Loop through all the bits
pszBits [nIndex] = pszBits [nIndex + 1]
Increment nIndex by 1
nCount = 0
Else
nCount = 0
12. Call the function fnBinary_to_ASCII () to get the ASCII values and the message
sent by the Transmitter.
13. Write those values into Output.txt.
33
4.2.3 Procedure:
In NetSim, Select “Programming Framing Sequence Bit Stuffing”.
The scenario will be obtained as shown below. Follow the steps.
Step 1:
In the left panel, select the Mode as Sample. Continue with the steps as shown below and
click Run.
So presently NetSim will run Bit Stuffing code already present in the software and will
display the result graphically
Select the Mode
Enter the Destination
address
Enter the Source
address
Enter the Data
Click run to execute
Click here to view the Concept,
Algorithm, Pseudo code and Flow
chart
Select the Error Condition
34
Result:
Step 2:
For user to write their own C Code in NetSim and check the result, click on Interface Source
Code (present in Help in the left pane).
Open Dev C++ or any GNU C compiler based IDK and copy the code from the Interface
Source Code.
In User Mode, the user needs to edit the Interface Source Code at the following location.
void fnBitStuffing()
{
// Write your own code here
}
So the user needs to add the user code, create exe and attach it with NetSim to run.
The User code which is to be added is given below:
void fnBitStuffing() { /////* User code part start */
int nCount = 0, nLoop1 = 0, nIndex = 0, nLoop2 = 0; int nLoop_Length = 0; char *pszBits; int nTotalLength; fnCheckSum_Calculation(); strcpy(szCheckSum_Sender, szCheckSum_Value); for (nLoop1 = g_nLength, nLoop2 = 0; nLoop1 < (g_nLength + MAX_CHECKSUM_DIGIT); nLoop1++, nLoop2++) { szBinaryValues[nLoop1] = szCheckSum_Sender[nLoop2]; } szBinaryValues[nLoop1] = '\0';
Output Data
35
//Merge all the Binary Values in Single Array pszBits = (char *)malloc(MAX_SIZE * sizeof(char)); strcpy(pszBits, szDestinationAddress); strcat(pszBits, szSourceAddress); strcat(pszBits, szBinaryValues); nTotalLength = strlen(pszBits); sz_Stuffed_DestinationAddress = (char *) malloc(15 * sizeof(char)); sz_Stuffed_SourceAddress = (char *)malloc(15 * sizeof(char)); sz_Stuffed_BinaryValues = (char *) malloc(MAXBITS * sizeof(char)); for(nLoop_Length = 0; nLoop_Length < nTotalLength; nLoop_Length++) { if(nLoop_Length >= 0 && nLoop_Length < 8) { if(pszBits[nLoop_Length] == '1') { nCount++; sz_Stuffed_DestinationAddress[nIndex] = '1'; if(nCount == 5) { nIndex++; sz_Stuffed_DestinationAddress[nIndex] = '0'; nCount = 0; } nIndex++; } else { nCount = 0; sz_Stuffed_DestinationAddress[nIndex] = '0'; nIndex++; } if(nLoop_Length == 7) { sz_Stuffed_DestinationAddress[nIndex] = '\0'; nIndex = 0; } } if(nLoop_Length >= 8 && nLoop_Length < 16) { if(pszBits[nLoop_Length] == '1') { nCount++; sz_Stuffed_SourceAddress[nIndex] = '1'; if(nCount == 5) { nIndex++; sz_Stuffed_SourceAddress[nIndex] = '0'; nCount = 0; } nIndex++; } else { nCount = 0; sz_Stuffed_SourceAddress[nIndex] = '0'; nIndex++; } if(nLoop_Length == 15) { sz_Stuffed_SourceAddress[nIndex] = '\0';
36
nIndex = 0; } } if(nLoop_Length >= 16 && nLoop_Length < nTotalLength) { if(pszBits[nLoop_Length] == '1') { nCount++; sz_Stuffed_BinaryValues[nIndex] = '1'; if(nCount == 5) { nIndex++; sz_Stuffed_BinaryValues[nIndex] = '0'; nCount = 0; } nIndex++; } else { nCount = 0; sz_Stuffed_BinaryValues[nIndex] = '0'; nIndex++; } sz_Stuffed_BinaryValues[nIndex] = '\0'; } } free(pszBits); /////* User code part end */ }
Create .exe file (Appendix 2: Creating .exe file using Dev C++)
In the left panel, select the Mode as User. Select the .exe file created above.
Repeat the steps done for Sample mode and click Run.
So presently NetSim will run Bit Stuffing code which is written by the user and will display
the result graphically.
In case of any error, “ERROR IN USER CODE” message will be displayed.
Note- How to practice this experiment without using NetSim
Users who do not have a licensed version of NetSim in their PC's, can practice as explained
below.
First, run the exercise in sample mode. The user would see that an Input.txt file is created in
Win OS temp folder (this can be reached by typing %temp%/NetSim in Windows run
window). This input file should be read by the user code and it should generate an Output.txt.
This Output.txt file is read by NetSim and shown graphically to the user.
37
User can follow the steps provided in Appendix 1: Programming exercise - How to practice
without NetSim.
Given below are sample Input.txt and Output.txt files for this experiment for users to verify
& validate their code.
Input.txt file contents
Destination Address=11111111
Source Address=01111110
Data=11111
CRC Polynomial=10011
Error status=0
Seed value=0
Output.txt file contents
Message=11111>
1=49>1=49>1=49>1=49>1=49>
Binary Values=0011000100110001001100010011000100110001>
CRC Polynomial=10011>
CheckSumSender=1010>
<Stuffing>
Destination Address=111110111>
Source Address=011111010>
Data=00110001001100010011000100110001001100011010>
<DeStuffing>
Destination Address=11111111>
Source Address=01111110>
Data=00110001001100010011000100110001001100011010>
Error Status=0>
CheckSumReceiver=0000>
Binary Values=0011000100110001001100010011000100110001>
1=49>1=49>1=49>1=49>1=49>
Message=11111>
*Note- Output.txt content will vary depending on the file contents.
38
4.3 Part B - Character Stuffing
4.3.1 Theory:
When data is transmitted, the transmitting node should distinguish between the start and the
end of the receiving node to read the data completely. This is accomplished by appending a
unique pattern of bit stream before and after the data.
Care is taken that this unique pattern does not occur in the data. If the pattern appears in the
data, it is broken. The process of appending a unique pattern and breaking the pattern is
known as framing.
Character stuffing is one of the framing methods, in which each frame starts with DLE STX
(Starting delimiter) character sequence and ends with DLE ETX (Ending delimiter) character
sequence.
Characters for DLE STX or DLE ETX may occur in the data. To solve this problem the
transmitting node inserts a DLE character just before each DLE character occurring in the
data.
4.3.2 Algorithm:
1. Get the Value of Starting Delimiter, Destination Address, Source Address, Data,
Checksum and Ending Delimiter by reading Input.txt.
2. Call the function fnCharacterStuffing () to do the character stuffing process.
3. Loop through all the bytes in Destination Address
Check szDestinationAddress [nLoop1] != „\0‟
sz_Stuffed_DestinationAddress [nIndex] = szDestinationAddress [nLoop1]
Increment nIndex by 1
Check szDestinationAddress [nLoop1] == szStartingDelimiter [0]
sz_Stuffed_DestinationAddress [nIndex] = szStartingDelimiter [0]
Increment nIndex by 1
Check szDestinationAddress [nLoop1] == szEndingDelimiter [0]
sz_Stuffed_DestinationAddress [nIndex] = szEndingDelimiter [0]
Increment nIndex by 1
Increment nLoop1 by 1
sz_Stuffed_DestinationAddress [nIndex] = '\0';
4. Similarly repeat step3 for Source Address, Data and Checksum.
5. Call the function fnDeStuffing () to do the destuffing process.
39
6. Copy all the bytes from Stuffed Destination Address to Destuffed Destination Address
7. Loop through all the bytes in Destuffed Destination Address
Check sz_Destuffed_DestinationAddress [nLoop1] != „\0‟
Check sz_Destuffed_DestinationAddress [nLoop1] ==
szStartingDelimiter [0] && sz_Destuffed_DestinationAddress [nLoop1] ==
szEndingDelimiter [0]
Check nIndex < strlen (sz_Destuffed_DestinationAddress)
sz_DeStuffed_DestinationAddress [nIndex] =
sz_DeStuffed_DestinationAddress [nIndex + 2];
Increment nIndex by 1
nIndex = 0
Else if sz_Destuffed_DestinationAddress [nLoop1] ==
szStartingDelimiter [0] || sz_Destuffed_DestinationAddress [nLoop1] ==
szEndingDelimiter [0]
Check nIndex < strlen (sz_Destuffed_DestinationAddress)
sz_DeStuffed_DestinationAddress [nIndex] =
sz_DeStuffed_DestinationAddress [nIndex + 1];
Increment nIndex by 1
nIndex = 0
Increment nLoop1 by 1
8. Similarly repeat step7 for Source Address, Data and Checksum and write those values
into Output.txt.
4.3.3 Procedure:
In NetSim, Select “Programming Framing Sequence Character Stuffing”.
The scenario will be obtained as shown below. Follow the steps.
Step 1:
In the left panel, select the Mode as Sample. Continue with the steps as shown below and
click Run.
So presently NetSim will run Character Stuffing code already present in the software and will
display the result graphically.
40
Click Run to execute
Select the mode
Enter starting
Delimiter
Click here to view the
Concept, Algorithm, Pseudo
code and Flow chart
Enter Destination
address
Enter Source Address
Enter input data
Enter Checksum
Enter ending delimiter
41
Result:
Step 2:
For user to write their own C Code in NetSim and check the result, click on Interface Source
Code (present in Help in the left pane).
Open Dev C++ or any GNU C compiler based IDK and copy the code from the Interface
Source Code.
In User Mode, the user needs to edit the Interface Source Code at the following location.
void fnCharacterStuffing()
{
// Write your own code here
}
So the user needs to add the user code, create exe and attach it with NetSim to run.
The User code which is to be added is given below
void fnCharacterStuffing() { /////* User code part start */ int nLoop1 = 0, nIndex = 0; sz_Stuffed_DestinationAddress = (char *)malloc(100 * sizeof(char)); sz_Stuffed_SourceAddress = (char *)malloc(100 * sizeof(char));
Character stuffed output
42
sz_Stuffed_Data = (char *)malloc(100 * sizeof(char)); sz_Stuffed_CheckSum = (char *)malloc(100 * sizeof(char)); while(szDestinationAddress[nLoop1] != '\0') { sz_Stuffed_DestinationAddress[nIndex] = szDestinationAddress[nLoop1]; nIndex++; if(szDestinationAddress[nLoop1] == szStartingDelimiter[0]) { sz_Stuffed_DestinationAddress[nIndex] = szStartingDelimiter[0]; nIndex++; } if(szDestinationAddress[nLoop1] == szEndingDelimiter[0]) { sz_Stuffed_DestinationAddress[nIndex] = szEndingDelimiter[0]; nIndex++; } nLoop1++; } sz_Stuffed_DestinationAddress[nIndex] = '\0'; nLoop1 = nIndex = 0; while (szSourceAddress[nLoop1] != '\0') { sz_Stuffed_SourceAddress[nIndex] = szSourceAddress[nLoop1]; nIndex++; if (szSourceAddress[nLoop1] == szStartingDelimiter[0]) { sz_Stuffed_SourceAddress[nIndex] = szStartingDelimiter[0]; nIndex++; } if (szSourceAddress[nLoop1] == szEndingDelimiter[0]) { sz_Stuffed_SourceAddress[nIndex] = szEndingDelimiter[0]; nIndex++; } nLoop1++; } sz_Stuffed_SourceAddress[nIndex] = '\0'; nLoop1 = nIndex = 0; while (szData[nLoop1] != '\0') { sz_Stuffed_Data[nIndex] = szData[nLoop1]; nIndex++; if (szData[nLoop1] == szStartingDelimiter[0]) { sz_Stuffed_Data[nIndex] = szStartingDelimiter[0]; nIndex++; } if (szData[nLoop1] == szEndingDelimiter[0]) { sz_Stuffed_Data[nIndex] = szEndingDelimiter[0]; nIndex++; } nLoop1++; } sz_Stuffed_Data[nIndex] = '\0'; nLoop1 = nIndex = 0; while (szCheckSum[nLoop1] != '\0') { sz_Stuffed_CheckSum[nIndex] = szCheckSum[nLoop1]; nIndex++;
43
if (szCheckSum[nLoop1] == szStartingDelimiter[0]) { sz_Stuffed_CheckSum[nIndex] = szStartingDelimiter[0]; nIndex++; } if (szCheckSum[nLoop1] == szEndingDelimiter[0]) { sz_Stuffed_CheckSum[nIndex] = szEndingDelimiter[0]; nIndex++; } nLoop1++; } sz_Stuffed_CheckSum[nIndex] = '\0'; free(szDestinationAddress); free(szSourceAddress); free(szData); free(szCheckSum); /////* User code part end */ }
Create .exe file (Appendix 2: Creating .exe file using Dev C++)
In the left panel, select the Mode as User. Select the .exe file created above.
Repeat the steps done for Sample mode and click Run.
So presently NetSim will run Character Stuffing code which is written by the user and will
display the result graphically.
In case of any error, “ERROR IN USER CODE” message will be displayed.
Note- How to practice this experiment without using NetSim
Users who do not have a licensed version of NetSim in their PC's, can practice as explained
below.
First, run the exercise in sample mode. The user would see that an Input.txt file is created in
Win OS temp folder (this can be reached by typing %temp%/NetSim in Windows run
window). This input file should be read by the user code and it should generate an Output.txt.
This Output.txt file is read by NetSim and shown graphically to the user.
User can follow the steps provided in Appendix 1: Programming exercise - How to practice
without NetSim.
Given below are sample Input.txt and Output.txt files for this experiment for users to verify
& validate their code
44
Input.txt file contents
Starting Delimiter=t
Destination Address=tetcosit
Source Address=welcomen
Data=netsimsw
Checksum=simulate
Ending Delimiter=o
Output.txt file contents
Stuffing>
Destination Address=ttettcoositt>
Source Address=welcoomen>
Data=nettsimsw>
Checksum=simulatte>
DeStuffing>
Destination Address=tetcosit>
Source Address=welcomen>
Data=netsimsw>
Checksum=simulate>
*Note- Output.txt content will vary depending on the file contents.
45
5. Client – Server Model
5.1 Objective:
Study of Socket Programming and Client – Server model
5.2 Theory:
The socket is a fundamental concept to the operation of TCP/IP application software. It is
also an interface between the application and the network. The exchange of data between a
pair of devices consists of a series of messages sent from a socket on one device to a socket
on other.
Once the socket is configured, the application can send the data using sockets for network
transmission and receive the data using sockets from the other host. A socket communication
can be connection oriented (TCP sockets) or connectionless (UDP sockets).
There is a receiver (TCP) server, which listens to the sender (TCP) client communications.
There can be two-way communication.
5.3 Algorithm:
Server:
1. Create a socket using address family (AF_INET), type (SOCK_STREM) and protocol
(TCP)
2. Initialize the address family, port no and IP address to communicate using sockets
3. Bind a local address and port number with a socket
4. Listen for an incoming socket connection
5. Accept an incoming connection attempt on a socket
6. Receive an incoming message
7. Write that incoming message to Output.txt
8. Send ACK to received socket
9. Call step 5 to receive the message once again
10. Close file
46
11. Close socket
Client:
1. Create a socket using address family (AF_INET), type (SOCK_STREM) and protocol
(TCP)
2. Initialize the address family, port no and IP address to communicate using sockets
3. Establish Connection with destination IP
4. Send the data using the socket id
5. Close the socket connection
5.4 Procedure:
Step:1
To begin with the experiment, open NetSim.
Click on Programming from the menu bar and select PC to PC Communication and then
select Socket Programming
When you select the User mode, you have to write your own program in C/C++, compile and
link to NetSim software for validation. Click on the F1 (Help) for details on how to proceed
with your own code.
The scenario will be obtained as shown below. Follow the steps
Select Mode
Select Protocol
Select Operation
Click Run to start
transmission
Click here to view Concept,
Algorithm, and Pseudo Code
& Flowchart
47
Under Input there are two things,
1. When Operation is Client, then the Server’s IP Address (Ex: 192.168.1.2) should
be given in the Server IP Address field.
2. When Operation is Server, then the Server’s IP Address (Ex: 192.168.1.2) would
be automatically filled in the Local IP Address field.
If the Operation is Server, the scenario will be obtained as shown below,
If the Operation is Client, the scenario will be obtained as shown below,
Server
Side
Client
Side
48
Step: 2
TCP
First the Server should click on the Run button after which the Client should click on
the Run button to Create the socket
Client should click on the Connect button to establish the connection with server.
The Client should click on the Send button to transmit the data to the Server.
The Client should click on the Close button to terminate the Connection with Server.
If the Data is successfully transmitted then the Sent Data would be Received in the
Server System.
UDP
First the Server should click on the Run button after which the Client should click on
the Run button to Create the socket
The Client should click on the Send button to transmit the data to the Server.
The Client should click on the Close button to terminate the Connection with Server.
If the Data is successfully transmitted then the Sent Data would be Received in the
Server System.
Enter Destination
IP Address Enter data to be
transmitted
49
5.5 Result:
User Mode (TCP)
For user to write their own C Code in NetSim and check the result, click on Interface Source
Code (present in Help in the left pane).
Open Dev C++ or any GNU C compiler based IDK and copy the code from the Interface
Source Code.
In User Mode, the user needs to edit the Interface Source Code at the following location.
int fnTcpServer()
{
// Write your own code here
return 0;
}
So the user needs to add the user code, create exe and attach it with NetSim to run.
The User code which is to be added is given below:-
int fnTcpServer()
{
/////* User code part start */
nSocketfd =(int) socket(AF_INET,SOCK_STREAM, 0);
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(SERVER_PORTNUMBER);
Received
data
50
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
nBindfd = bind(nSocketfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
#ifndef _NETSIM_SAMPLE
nListenfd = listen(nSocketfd, 5);
#else
nListenfd = listen(nSocketfd, 1);
#endif
nServerLen = sizeof(serv_addr);
if (fnWriteOutput() == 1)
{ /*if socket creation,bind and listen failed function will terminate*/
closesocket(nSocketfd);
return 0;
}
#ifndef _NETSIM_SAMPLE
nNewsocketfd =(int) accept(nSocketfd, (struct sockaddr *) &cli_addr,
&nServerLen);
nLoopCount++;
memset(szData, 0, sizeof(szData)); /*Clear the array*/
nReceivedbytes =(int) recv(nNewsocketfd, szData, sizeof(szData), 0);
fnWriteOutput();
nSendbytes =(int) send(nNewsocketfd, pszBuffer, strlen(pszBuffer), 0);
#else
while (1)
{
nNewsocketfd =(int) accept(nSocketfd, (struct sockaddr *) &cli_addr,
&nServerLen);
nLoopCount++;
memset(szData, 0, sizeof(szData)); /*Clear the array*/
nReceivedbytes =(int) recv(nNewsocketfd, szData, sizeof(szData), 0);
fnWriteOutput();
nSendbytes =(int) send(nNewsocketfd, pszBuffer, strlen(pszBuffer), 0);
if( nTCPServerCloseFlag == 1) /*break the loop when user send close the
connection*/
break;
}
#endif
closesocket(nSocketfd);
////* User code part end */
return 0;
}
User Mode (UDP)
For user to write their own C Code in NetSim and check the result, click on Interface Source
Code (present in Help in the left pane).
Open Dev C++ or any GNU C compiler based IDK and copy the code from the Interface
Source Code.
51
In User Mode, the user needs to edit the Interface Source Code at the following location.
int fnUdpServer()
{
// Write your own code here
return 0;
}
So the user needs to add the user code, create exe and attach it with NetSim to run.
The User code which is to be added is given below
int fnUdpServer()
{
/////* User code part start */
nSocketfd = (int)socket(AF_INET,SOCK_DGRAM, 0); /*Server side socket
creation*/
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(SERVER_PORTNUMBER); /* Server port number 6000*/
nServerLen = sizeof(serv_addr);
nBindfd = bind(nSocketfd, (struct sockaddr *) &serv_addr,
sizeof(serv_addr));
fnWriteOutput();
#ifndef _NETSIM_SAMPLE
memset(szData, 0, sizeof(szData)); //Clear the array
nReceivedbytes = recvfrom(nSocketfd, szData, sizeof(szData), 0,(struct
sockaddr *) &serv_addr, &nServerLen);
fnWriteOutput();
#else
while(1)
{
memset(szData, 0, sizeof(szData)); //Clear the array
nReceivedbytes = recvfrom(nSocketfd, szData, sizeof(szData), 0,(struct
sockaddr *) &serv_addr, &nServerLen);
fnWriteOutput();
}
#endif
closesocket(nSocketfd);
/////* User code part end */
return 0;
}
Create .exe file (Appendix 2: Creating .exe file using Dev C++)
In the left panel, select the Mode as User. Select the .exe file created above.
Repeat the steps performed for Sample Mode and click Run.
52
So presently NetSim will execute code written by the user and will display the result
graphically.
In case of any error, “ERROR IN USER CODE” message will be displayed.
Note- How to practice this experiment without using NetSim
Users who do not have a licensed version of NetSim in their PC's, can practice as explained
below.
First, run the exercise in sample mode. The user would see that an Input.txt file is created in
Win OS temp folder (this can be reached by typing %temp%/NetSim in Windows run
window). This input file should be read by the user code and it should generate an Output.txt.
This Output.txt file is read by NetSim and shown graphically to the user.
User can follow the steps provided in Appendix 1: Programming exercise - How to practice
without NetSim.
Given below are sample Input.txt and Output.txt files for this experiment for users to verify
& validate their code. User must run the exe at both client and server and use the respective
Input.txt file. Inside Input.txt file at Client system, use the server system IP address in
“Destination IP Address” and client system IP address instead of “192.168.0.147:-Hello
World”
For TCP
Input.txt file contents at Server system
Protocol=TCP
Operation=Server
Input.txt file contents at Client system
Protocol=TCP
Operation=Client
Destination IP Address=192.168.0.130
192.168.0.147:-Hello World
Output.txt file contents at Server system
Socket Created
Bind Succeed
Listen Succeed
For UDP
Input.txt file contents at Server system
Protocol=UDP
Operation=Server
Input.txt file contents at Client system
Protocol=UDP
Operation=Client
Destination IP Address=192.168.0.130
192.168.0.147:-Hello World
Output.txt file contents at Server
system
Socket Created
Bind Succeed
53
6. Socket Program for Talk
6.1 Objective:
Write a socket Program for Echo/Ping/Talk commands.
6.2 Theory:
The socket is a fundamental concept to the operation of TCP/IP application software. It is
also an interface between the application and the network. The exchange of data between a
pair of devices consists of a series of messages sent from a socket on one device to a socket
on other. Once the socket is configured, the application can send the data using sockets for
network transmission and receive the data using sockets from the other host. A socket
communication can be connection oriented (TCP sockets) or connectionless (UDP sockets).
There is a receiver (TCP/UDP), which listens to the sender (TCP/UDP) communications.
There can be two-way communication.
6.3 Algorithm
6.3.1 Send
1. Create a socket using address family (AF_INET), type (SOCK_STREM) and protocol
(TCP)
2. Initialize the address family, port no and IP address to communicate using sockets.
3. Establish Connection with destination IP
4. While new messages are typed by user
4.1. Send the data using the socket id
5. Close the socket connection if user types “<close>”
6.4 Procedure:
To begin with the experiment, open NetSim
Click on Programming from the menu bar and select PC to PC Communication and then
select Chat Application
When you select the User mode, you have to write your own program in C/C++, compile and
link to NetSim software for validation. Click on the F1 (Help) for details on how to proceed
with your own code.
54
The scenario will be obtained as shown below. Follow the steps
Step 1:
Step 2:
Select Mode
Select Protocol
Enter Destination IP address
Enter User Name
Click Run to start
transmission
Click here to view Concept,
Algorithm, and Pseudo Code
& Flowchart
Enter the data to
send
Click Send
Button
55
Step 3:
User Mode (TCP)
In User Mode, the user needs to edit the Interface Source Code at the following location.
int fnTcpSend()
{
// Write your own code here
fnWriteOutput_TCP_Send();
return 0;
}
So the user needs to add the user code, create exe and attach it with NetSim to run.
The User code which is to be added is given below
int fnTcpSend()
{
/////* User code part start */
int nSendbytes;
nSocketfd = socket(AF_INET,SOCK_STREAM, 0);
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORTNUMBER );
serv_addr.sin_addr.s_addr = inet_addr(server_ip);
nConnectfd = connect(nSocketfd, (struct sockaddr *)
&serv_addr,sizeof(serv_addr));
while(getnewmessage())
{
nSendbytes = send(nSocketfd, szData, strlen(szData), 0);
_strupr(szData);
Receiver Data
56
if(!strcmp(szData,closedata))
break;
}
closesocket(nSocketfd);
/////* User code part end */
return 0;
}
User Mode (UDP)
In User Mode, the user needs to edit the Interface Source Code at the following location.
int fnUdpSend()
{
// Write your own code here
fnWriteOutput_UDPSend();
return 0;
}
So the user needs to add the user code, create exe and attach it with NetSim to run.
The User code which is to be added is given below
int fnUdpSend()
{
/////* User code part start */
int nSendbytes;
nSocketfd = socket(AF_INET,SOCK_DGRAM, IPPROTO_UDP);
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORTNUMBER );
serv_addr.sin_addr.s_addr = inet_addr(server_ip);
nServerLen = sizeof(serv_addr);
while(getnewmessage())
{
nSendbytes = sendto(nSocketfd, szData, strlen(szData), 0,(struct
sockaddr *) &serv_addr, nServerLen);
if(nSendbytes < 0)
{
fprintf(fpOutput,"Could not receive : %d\n" ,
WSAGetLastError());
fflush(fpOutput);
return -1;
}
_strupr(szData);
if(!strcmp(szData,closedata))
break;
}
closesocket(nSocketfd); /* close the socket*/
57
/////* User code part end */
return 0;
}
Note- How to practice this experiment without using NetSim
Users who do not have a licensed version of NetSim in their PC's, can practice as explained
below.
First, run the exercise in sample mode. The user would see that an Input.txt file is created in
Win OS temp folder (this can be reached by typing %temp%/NetSim in Windows run
window). This input file should be read by the user code and it should generate an Output.txt.
This Output.txt file is read by NetSim and shown graphically to the user.
User can follow the steps provided in Appendix 1: Programming exercise - How to practice
without NetSim.
Note
Given below are sample Input.txt and Output.txt files for this experiment for users to verify
& validate their code. Both the user must run the exe at the same time and use the respective
Input.txt file. Inside Input.txt file at both the user, set the ServerIp as the IP address of the
other user.
For TCP
Input.txt file contents at Chat user 1
Protocol=TCP
ServerIp=192.168.0.134
Input.txt file contents at Chat user 2
Protocol=TCP
ServerIp=192.168.0.145
Output.txt file contents at both Chat user 1 and 2
Socket created
Bind done
Listen completed
Waiting for client to connect...
Connected to client
58
For UDP
Input.txt file contents at Chat user 1
Protocol= UDP
ServerIp=192.168.0.134
Input.txt file contents at Chat user 2
Protocol=UDP
ServerIp=192.168.0.145
Output.txt file contents at both Chat user 1 and 2
Socket created
Bind done
59
7. CSMA/CA and CSMA/CD
7.1 Objective:
To create scenario and study the performance of network with CSMA / CA protocol and
compare with CSMA/CD protocols.
7.2 Part A – CSMA/CA
7.2.1 Theory:
Wireless LAN is basically a LAN that transmits data over air, without any physical
connection between devices. The transmission medium is a form of electromagnetic
radiation. Wireless LAN is ratified by IEEE in the IEEE 802.11 standard. In most of the
WLAN products on the market based on the IEEE 802.11b technology the transmitter is
designed as a Direct Sequence Spread Spectrum Phase Shift Keying (DSSS PSK) modulator,
which is capable of handling data rates of up to 11 Mbps. The underlying algorithm used in
Wireless LAN is known as the CSMA/CA – Carrier Sense Multiple Access/Collision
Avoidance algorithm.
7.2.2 Procedure:
How to Create Scenario & Generate Traffic:
Please navigate through the below given path to,
Create Scenario: New Internetworks”.
7.2.2.1 Sample Inputs:
Follow the steps given in the different samples to arrive at the objective.
In this Sample,
Total no of APs (Access Points) used: 1
Total no of Wireless Nodes used: 5
60
The AP and Wireless Nodes are interconnected as shown below:
Set the below properties for AP, Wireless Nodes and Wireless Link and Application
properties.
Click and drop the Application, set properties and run the simulation.
Inputs for the Sample experiment are given below:
Access Point Properties: In the Experiment, for AP, the following properties have to be set
by Right clicking on the AP Properties
Global Properties
X/Lat 150
Y/Lon 110
Interface1_WLAN Properties
RTS_Threshold 1000
Wireless Link Properties: Set Channel Characteristics as No Path Loss
Wireless Node Properties: In the Experiment, for each Wireless Node, the following
properties have to be set by Right clicking on the Wireless Node Properties.
61
Global Properties
2(Wireless Node B)
X/Lat 125
Y/Lon 130
3(Wireless Node C)
X/Lat 150
Y/Lon 140
4(Wireless Node D)
X/Lat 170
Y/Lon 135
5(Wireless Node E)
X/Lat 185
Y/Lon 125
6(Wireless Node F)
X/Lat 180
Y/Lon 105
For all wireless Nodes, set the below properties
Wireless Node Properties All Nodes
Transport Layer Properties
TCP Disable
Interface1_Wireless Properties
RTS_Threshold 1000
Application Properties:
Select the Application Button and click on the gap between the Grid Environment and the
ribbon. Now right click on Application and select Properties.
62
NOTE: The procedure to create multiple applications are as follows:
Step 1: Click on the ADD button present in the bottom left corner to add a new application.
Application Properties
Source_ID 2(Wireless
Node B)
3(Wireless
Node C)
4(Wireless
Node D)
5(Wireless
Node E)
6(Wireless
Node F)
Destination_ID 3(Wireless
Node C)
4(Wireless
Node D)
5(Wireless
Node E)
6(Wireless
Node F)
2 (Wireless
Node B)
Application Type Custom Custom Custom Custom Custom
Packet Size
Distribution Constant Constant Constant Constant Constant
Value (bytes) 1472 1472 1472 1472 1472
Packet Inter Arrival Time
Distribution Constant Constant Constant Constant Constant
Value (micro secs) 10000 10000 10000 10000 10000
Simulation Time - 100 Sec
(Note: The Simulation Time can be selected only after the following two tasks,
Set the properties for the Wireless Nodes, AP, Wireless Link and Application.
Click on Run Simulation button.
63
7.3 Part B - CSMA/CD
7.3.1 Theory:
Carrier Sense Multiple Access Collision Detection (CSMA / CD)
This protocol includes the improvements for stations to abort their transmissions as soon as
they detect a collision. Quickly terminating damaged frames saves time and bandwidth. This
protocol is widely used on LANs in the MAC sub layer. If two or more stations decide to
transmit simultaneously, there will be a collision. Collisions can be detected by looking at the
power or pulse width of the received signal and comparing it to the transmitted signal. After a
station detects a collision, it aborts its transmission, waits a random period of time and then
tries again, assuming that no other station has started transmitting in the meantime.
7.3.2 Procedure:
How to create a scenario and generate traffic:
Create Scenario: New Legacy Networks CSMA/CD
7.3.2.1 Sample Inputs:
To perform this sample experiment, five nodes and one
hub are considered.
Click and drop Hub on the environment builder.
Click and drop 5 Wired Nodes.
Connect the Wired nodes to the hub through Wired
link as shown in figure.
64
In the Experiment, for each Node, the following properties have to be set by Right clicking
on the Node Properties.
Hub Properties: Accept default properties of Hub.
Application Properties:
Select the Application Button and click on the gap between the Grid Environment and the
ribbon. Now right click on Application and select Properties.
NOTE: The procedure to create multiple applications are as follows:
Step 1: Click on the ADD button present in the bottom left corner to add a new application.
65
Application Properties
Source_ID 2(Wireless
Node B)
3(Wireless
Node C)
4(Wireless
Node D)
5(Wireless
Node E)
6(Wireless
Node F)
Destination_ID 3(Wireless
Node C)
4(Wireless
Node D)
5(Wireless
Node E)
6(Wireless
Node F)
2 (Wireless
Node B)
Application Type Custom Custom Custom Custom Custom
Packet Size
Distribution Constant Constant Constant Constant Constant
Value (bytes) 1472 1472 1472 1472 1472
Packet Inter Arrival Time
Distribution Constant Constant Constant Constant Constant
Value (micro secs) 10000 10000 10000 10000 10000
Simulation Time - 100 Sec
(Note: The Simulation Time can be selected only after the following two tasks,
Set the properties for the Nodes & The Hub
Click on Run Simulation button).
7.3.3 Result:
(Throughput Comparison between CSMA/CA and CSMA/CD protocols)
0
1
2
3
4
5
6
7
CSMA/CA CSMA/CD
Thro
ugh
pu
t(M
bp
s)
Throughput
66
(Collision count comparison between CSMA/CA and CSMA/CD protocols)
7.3.4 Inference:
In case of wireless LAN, an acknowledgment packet is transmitted by the receiver node to
the transmitter. Moreover, WLAN is an infrastructure based network i.e. a centralized device
(Access Point) is controlling the network. Hence all the packets are transmitted to the
destination via the Access Point (AP) i.e. packets transmitted by the source are first received
by AP, which is then retransmitted by the AP to the destination. Furthermore, wireless
links/medium supports half-duplex transmission. Due to this nature of packet hopping,
acknowledgment overheads and transmission, the throughput is less compared to Ethernet.
Unlike CSMA/CD (Carrier Sense Multiple Access/Collision Detect) which deals with
transmissions after a collision has occurred, CSMA/CA acts to prevent collisions before they
happen. The collision avoidance concept in wireless LAN protocol, avoids the possibility of
collision of data frames. In CSMA/CA, as soon as a node receives a packet that is to be sent,
it checks to be sure the channel is clear (no other node is transmitting at the time). If the
channel is clear, then the packet is sent. If the channel is not clear, the node waits for a
randomly chosen period of time, and then checks again to see if the channel is clear. This is
the primary reason for wireless LAN having less collision count than Ethernet. In addition,
RTS/CTS is also implemented to reduce collision.
0
10000
20000
30000
40000
50000
60000
70000
CSMA/CA CSMA/CD
No
. of
Pac
kets
Collision count
67
8. Network Topology –Star, Bus, Ring
8.1 Part A- Star
8.1.1 Theory:
In local area networks with a star topology, each network host is connected to a central
switch with a point-to-point connection. In Star topology every node (computer workstation
or any other peripheral) is connected to central node called switch. The switch is the server
and the peripherals are the clients. The network does not necessarily have to resemble a star
to be classified as a star network, but all of the nodes on the network must be connected to
one central device. All traffic that traverses the network passes through the central switch.
The star topology is considered the easiest topology to design and implement. An advantage
of the star topology is the simplicity of adding additional nodes.
8.2 Procedure:
How to Create Scenario & Generate Traffic:
Please navigate through the below given path to,
Create Scenario: “Simulation New Internetworks”.
Sample Inputs:
Follow the steps given in the different samples to arrive at the objective.
In this Sample,
Total no of switch used: 1
Total no of Wired Nodes used: 6
The switch and Wired Nodes are interconnected as shown below:
68
Set the below properties for switch, Wired node and Wired Link.
Click and drop the Application, set properties and run the simulation.
Inputs for the Sample experiment are given below:
Switch Properties: Accept the default properties of switch
Wired Node Properties:
Wired Node Properties All Nodes
Transport Layer Properties
TCP Disable
Wired Link Properties:
Wired Link Properties All Links
Uplink Speed (Mbps) 100
Downlink Speed(Mbps) 100
Uplink BER No Error
Downlink BER No Error
69
Application Properties:
Application
Properties
2(Wired
Node B)
3(Wired
Node C)
4(Wired
Node D)
5(Wired
Node E)
6(Wired
Node F)
7(Wired
Node F)
Destination 3(Wired
Node C)
4(Wired
Node D)
5(Wired
Node E)
6(Wired
Node F)
7(Wired
Node B)
2(Wired
Node B)
Application Type Custom Custom Custom Custom Custom Custom
Packet Size
Distribution Constant Constant Constant Constant Constant Constant
Packet Size (Bytes) 10000 10000 10000 10000 10000 10000
Packet Inter Arrival Time
Distribution Constant Constant Constant Constant Constant Constant
Packet Inter
Arrival Time (µs)
1000 1000 1000 1000 1000 1000
Simulation Time - 10 Sec
(Note: The Simulation Time can be selected only after the following two tasks,
Set the properties for the Switch, Wired Node, Wired Link and Application.
Click on Run Simulation button).
70
8.3 Part B- Token Bus
8.3.1 Theory:
Token bus is a LAN protocol operating in the MAC layer. Token bus is standardized as per
IEEE 802.4. Token bus can operate at speeds of 5Mbps, 10 Mbps and 20 Mbps. The
operation of token bus is as follows
Unlike token ring in token bus the ring topology is virtually created and maintained by the
protocol. A node can receive data even if it is not part of the virtual ring, a node joins the
virtual ring only if it has data to transmit. In token bus data is transmitted to the destination
node only where as other control frames is hop to hop. After each data transmission there is a
solicit_successsor control frame transmitted which reduces the performance of the protocol.
8.3.2 Procedure:
How to create a scenario and generate traffic:
Create Scenario: “Simulation New Legacy NetworkToken Bus”.
Sample Input:
In this Sample experiment 6 Nodes and 1 Hub need to be clicked and dropped onto the
Environment Builder.
71
Application Properties:
Application
Properties
2(Wired
Node B)
3(Wired
Node C)
4(Wired
Node D)
5(Wired
Node E)
6(Wired
Node F)
7(Wired
Node F)
Destination 3(Wired
Node C)
4(Wired
Node D)
5(Wired
Node E)
6(Wired
Node F)
7(Wired
Node B)
2(Wired
Node B)
Application Type Custom Custom Custom Custom Custom Custom
Packet Size
Distribution Constant Constant Constant Constant Constant Constant
Packet Size (Bytes) 10000 10000 10000 10000 10000 10000
Packet Inter Arrival Time
Distribution Constant Constant Constant Constant Constant Constant
Packet Inter
Arrival Time (µs)
1000 1000 1000 1000 1000 1000
Link Properties:
Link Properties Values to be Selected
Error Rate (bit error rate) 0
Simulation Time - 10 Sec
(Note: The Simulation Time can be selected only after the following two tasks,
Set the properties for the Nodes & The Hub
Click on Run Simulation button).
72
8.4 Part C - Token Ring
8.4.1 Theory
Token ring is a LAN protocol operating in the MAC layer. Token ring is standardized as per
IEEE 802.5. Token ring can operate at speeds of 4mbps and 16 mbps. The operation of token
ring is as follows
When there is no traffic on the network a simple 3-byte token circulates the ring. If the token
is free (no reserved by a station of higher priority as explained later) then the station may
seize the token and start sending the data frame. As the frame travels around the ring ach
station examines the destination address and is either forwarded (if the recipient is another
node) or copied. After copying4 bits of the last byte is changed. This packet then continues
around the ring till it reaches the originating station. After the frame makes a round trip the
sender receives the frame and releases a new token onto the ring.
8.4.2 Procedure
How to create a scenario and generate traffic:
Create Scenario: “Simulation New Legacy NetworkToken Ring”.
73
Sample Input
In this Sample experiment 6 Nodes and 1 Concentrator need to be clicked and dropped onto
the Environment Builder.
Application Properties:
Application
Properties
2(Wired
Node B)
3(Wired
Node C)
4(Wired
Node D)
5(Wired
Node E)
6(Wired
Node F)
7(Wired
Node F)
Destination 3(Wired
Node C)
4(Wired
Node D)
5(Wired
Node E)
6(Wired
Node F)
7(Wired
Node B)
2(Wired
Node B)
Application Type Custom Custom Custom Custom Custom Custom
Packet Size
Distribution Constant Constant Constant Constant Constant Constant
Packet Size (Bytes) 10000 10000 10000 10000 10000 10000
Packet Inter Arrival Time
Distribution Constant Constant Constant Constant Constant Constant
Packet Inter
Arrival Time (µs)
1000 1000 1000 1000 1000 1000
Concentrator Properties:
Concentrator Properties Values to be Selected
Data Rate(Mbps) 16
Error Rate (bit error rate) No error
Simulation Time - 10 Sec
(Note: The Simulation Time can be selected only after the following two tasks,
Set the properties for the Nodes & The Hub
Click on Run Simulation button).
74
8.5 Result
Throughput Comparison between Bus, Ring and Star
8.6 Inference
Due to more overheads and complicated ring maintenance procedure token bus always less
than token rings. Star topology throughput is higher than other topology (Bus and Ring)
because Star has higher data rate.
0
10
20
30
40
50
60
70
80
90
Bus Ring Star
Thro
ugh
pu
t
Sample Experiments
Throughput
75
9. Distance Vector Routing
Objective: Write a C/C++ program to verify the distance vector routing algorithm
9.1 Theory
Distance Vector Routing is one of the routing algorithms used in a Wide Area Network for
computing shortest path between source and destination. 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
certain number of exchanges, all routers will have the full routing information about the area
of the network. After each table exchange, router re-computes the shortest path between the
routers. The algorithm used for this routing is called Distance Vector Routing.
9.2 Algorithm
Repeat the following steps until there is no change in the routing table for all routers.
Take the Next Router routing table and its neighbor routing table.
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.
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.
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.
Write the next stage of routing table into the file.
76
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.
9.3 Procedure:
To begin with the experiment, open NetSim
Click on Programming from the menu bar and select Distance Vector Routing
Step 1:
The scenario will be obtained as shown below. Follow the steps.
When you select the User mode, you have to write your own program in C/C++, compile and
link to NetSim software for validation. Click on the F1 (Help) for details on how to proceed
with your own code.
Select the Mode
Click Run to execute the Program
Connect the Routers
77
9.4 Results (to be filled up by the students):
Step 2:
For user to write their own C Code in NetSim and check the result, click on Interface Source
Code (present in Help in the left pane).
Open Dev C++ or any GNU C compiler based IDK and copy the code from the Interface
Source Code.
The user needs to edit the Interface Source Code at the following location.
void fnDistVectAlgorithm()
{
// Write your own code here
}
So the user needs to add the user code, create exe and attach it with NetSim to run.
Output Table
78
The User code which is to be added is given below:-
void fnDistVectAlgorithm()
{
/////* User code part start */
do// This do while... loop is to update the table information till it
knows all the router's information present in the network.
{
// I for//To go to No of router
for(nRouterTable=1;nRouterTable<=g_nNoOfRouters;nRouterTable++)
{// II for //Select the source router
for(nNeighbour=1;nNeighbour<=g_nNoOfRouters;nNeighbour++)
{// III for//move to all router
if(Table[nRouterTable].nCostID[nNeighbour]==1)
{// I if //select the neigh router
int nDestID=1;
for(nDestID=1;nDestID<=g_nNoOfRouters;nDestID++)
{// IV for //select the routing table of
neigh
if(nDestID!=nRouterTable)
{// II if
if((Table[nRouterTable].nDestID[nDestID] == 0) &&
(Table[nNeighbour].nDestID[nDestID]!=0))// ||
{// III if //This loop is to
check whether the neighbour router is DESTINATION or not.
Table[nRouterTable].nDestID[nDestID] = nDestID;
Table[nRouterTable].nNextHop[nDestID] = nNeighbour;
Table[nRouterTable].nCostID[nDestID]=(Table[nNeighbour].nCostID[nDestID]+1);
}
else
if((Table[nRouterTable].nNextHop[nDestID]!=nDestID||Table[nRouterTable].nCostID[nDe
stID]!=1)&&(Table[nNeighbour].nDestID[nDestID]!=0))
{// else if
// This loop is to check
whether the neighbour router is the destination or not and also check whether the
cost ID is 1 or not.
if(Table[nRouterTable].nCostID[nDestID]>Table[nNeighbour].nCostID[nDestID])
{//IV if
//This loop is to find
the least cost path
Table[nRouterTable].nDestID[nDestID] = nDestID;
Table[nRouterTable].nNextHop[nDestID] = nNeighbour;
Table[nRouterTable].nCostID[nDestID]=(Table[nNeighbour].nCostID[nDestID]+1);
}//end IV if
}//end else if
}// end II if
}//end IV for
}// end I if
}//end III for
79
}// end II for
nStage++;
fnDisplay(nStage);
}while(nStage<2);
/////* User code part end */
}
Create .exe file (Appendix 2: Creating .exe file using Dev C++)
In the left panel, select the Mode as User. Select the .exe file created above.
Click on 1 router and another router consecutively to connect them. Click Run.
So presently NetSim will run Distance Vector Routing code which is written by the user and
will display the result graphically.
In case of any error, “ERROR IN USER CODE” message will be displayed.
Note- How to practice this experiment without using NetSim
Users who do not have a licensed version of NetSim in their PC's, can practice as explained
below.
First, run the exercise in sample mode. The user would see that an Input.txt file is created in
Win OS temp folder (this can be reached by typing %temp%/NetSim in Windows run
window). This input file should be read by the user code and it should generate an Output.txt.
This Output.txt file is read by NetSim and shown graphically to the user.
User can follow the steps provided in Appendix 1: Programming exercise - How to practice
without NetSim.
Given below are sample Input.txt and Output.txt files for this experiment for users to verify
& validate their code
Input.txt file contents
Router_ID=1>Router_Name=Router_1>No_Of_Neighbour=1>Neighbours_ID=2
Router_ID=2>Router_Name=Router_2>No_Of_Neighbour=4>Neighbours_ID=1>3>6>5
Router_ID=3>Router_Name=Router_3>No_Of_Neighbour=2>Neighbours_ID=2>4
Router_ID=4>Router_Name=Router_4>No_Of_Neighbour=2>Neighbours_ID=3>6
Router_ID=5>Router_Name=Router_5>No_Of_Neighbour=1>Neighbours_ID=2
Router_ID=6>Router_Name=Router_6>No_Of_Neighbour=2>Neighbours_ID=4>2
80
Output.txt file contents
0>1>2>1>0
0>2>1>1>0
0>2>3>1>0
0>2>5>1>0
0>2>6>1>0
0>3>2>1>0
0>3>4>1>0
0>4>3>1>0
0>4>6>1>0
0>5>2>1>0
0>6>2>1>0
0>6>4>1>0
1>1>2>1>0
1>1>3>2>2
1>1>5>2>2
1>1>6>2>2
1>2>1>1>0
1>2>3>1>0
1>2>4>2>6
1>2>5>1>0
1>2>6>1>0
1>3>1>2>2
1>3>2>1>0
1>3>4>1>0
1>3>5>2>2
1>3>6>2>4
1>4>1>3>3
1>4>2>2>6
1>4>3>1>0
1>4>5>3>3
1>4>6>1>0
1>5>1>2>2
1>5>2>1>0
1>5>3>2>2
1>5>4>3>2
1>5>6>2>2
1>6>1>2>2
1>6>2>1>0
1>6>3>2>4
1>6>4>1>0
1>6>5>2>2
2>1>2>1>0
2>1>3>2>2
2>1>4>3>2
2>1>5>2>2
2>1>6>2>2
2>2>1>1>0
2>2>3>1>0
81
2>2>4>2>6
2>2>5>1>0
2>2>6>1>0
2>3>1>2>2
2>3>2>1>0
2>3>4>1>0
2>3>5>2>2
2>3>6>2>4
2>4>1>3>6
2>4>2>2>6
2>4>3>1>0
2>4>5>3>6
2>4>6>1>0
2>5>1>2>2
2>5>2>1>0
2>5>3>2>2
2>5>4>3>2
2>5>6>2>2
2>6>1>2>2
2>6>2>1>0
2>6>3>2>4
2>6>4>1>0
2>6>5>2>2
82
10. Link State Routing
Objective: Write a C/C++ program to verify the Link state routing Algorithm.
10.1 Theory:
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).
Link state algorithm is a method used to find the shortest path between a source router and a
destination router based on the distance and route the packets through that route.
10.2 Algorithm:
1. Start with the router: the root of the tree
2. Assign a cost of 0 to this router and make it the first permanent router.
3. Examine each neighbor router of the router that was the last permanent router.
4. Assign a cumulative cost to each router and make it temporary.
5. Among the list of temporary routers
5. a. Find the router with the smallest cumulative cost and make it permanent.
5. b. If a router can be reached from more than one direction
5. b. 1. Select the direction with the shortest cumulative cost.
6. Repeat steps 3 to 5 until every router becomes permanent.
10.3 Procedure:
Step 1:
To begin with the experiment, open NetSim
Click on Programming from the menu bar and select Shortest Path. In shortest path select
Link State Routing algorithm.
83
The scenario will be obtained as shown below. Follow the steps.
When you select the User mode, you have to write your own program in C/C++, compile and
link to NetSim software for validation. Click on F1 (Help) link for details on how to proceed
with your own code.
10.4 Results (to be filled up by the students):
Connect the Routers
Click Run to execute the Program
Select Link State
Select Mode
Output
table
84
Inference (to be filled up by the students):
Here, Router 1 is taken as the source and Router 3 as the destination. The paths are connected
with input as the distance. The figure indicated in green line shows the shortest path.
Step 2:
For user to write their own C Code in NetSim and check the result, click on Interface Source
Code (present in Help in the left pane).
Open Dev C++ or any GNU C compiler based IDK and copy the code from the Interface
Source Code.
The user needs to edit the Interface Source Code at the following location.
void fnDijkstra()
{
// Write your own code here
}
So the user needs to add the user code, create exe and attach it with NetSim to run.
The User code which is to be added is given below
void fnDijkstra() { /////* User code part start */
//Write your own code for Link State Algorithm HERE
int i, j; // Temporary loop variables char szString[_MEM_BUFFER2]; char* szToken; int iNo; //total number of nodes used in the graph. pszFile = (char*) malloc(sizeof(char) * _MEM_BUFFER2); szInput_path = (char*) malloc(_MEM_BUFFER2 * sizeof(char)); strcpy(szInput_path, szTempPath); strcat(szInput_path, "/Input.txt"); strcpy(pszFile, szInput_path); fp = fopen(pszFile, "r"); szToken = (char*) malloc(sizeof(_MEM_BUFFER2)); fgets(szString, _MEM_BUFFER2, fp);//skip the first line fgets(szString, _MEM_BUFFER2, fp); szToken = strtok(szString, "="); szToken = strtok(NULL, "="); iNo = atoi(szToken); strcpy(pszFile, ""); strcpy(pszFile, szOutput_path); fpOutput = fopen(pszFile, "w+");
85
if (iNo <= 11) { fnInitialize(iNo); } else { fclose(fp); } for (i = 0; i < iNo; i++) { for (j = 0; j < iNo; j++) { distanceMatrix[i][j] = 999; } } strcpy(pszFile, szInput_path); fp = fopen(pszFile, "r"); fgets(szString, _MEM_BUFFER2, fp); fgets(szString, _MEM_BUFFER2, fp); fgets(szString, _MEM_BUFFER2, fp);//skip first three line from input.txt //parsing the input file and storing the values into distance matrix for (i = 0; i < iNo; i++) { fgets(szString, _MEM_BUFFER2, fp); szToken = strtok(szString, ">"); j = 0; while (szToken != NULL) { /* While there are tokens in "string" */ if (atoi(szToken) == 999) { // 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, _MEM_BUFFER2, fp); szToken = strtok(szString, "="); szToken = strtok(NULL, "="); source = atoi(szToken); --source; // Tokenizing for the destination node
fgets(szString, _MEM_BUFFER2, fp); szToken = strtok(szString, "="); szToken = strtok(NULL, "="); destination = atoi(szToken); --destination; fclose(fp); // Initializing the Path Array and The Include Array
// For Include Array
for (i = 0; i < iNo; i++) { if (i == source) include[i] = 1; else
86
include[i] = 0; }//end of for loop // For Distance Array for (i = 0; i < iNo; i++) { if (i == source) distance[i] = 0; else { if (distanceMatrix[source][i] == 999) { distance[i] = 999; } else { distance[i] = distanceMatrix[source][i]; } } }//end of for loop // For Initialising Path Array for (i = 0; i < iNo; i++) { if (distanceMatrix[source][i] == 999) { path[i] = 999; } else { path[i] = source; } }//end of for loop iFlag = 0; //main iteration phase for Dijkstra's Algorithm while (iFlag == 0) { //find out the minimum distance from the availabe nodes not included
min = 999; node = 999; for (i = 0; i < iNo; i++) { if (include[i] == 0) { if (min == 999) { min = distance[i]; node = i; } else { if ((distance[i] < min) && (distance[i] != 999)) { min = distance[i]; node = i; } } } } if (node != 999) include[node] = 1;
// Checking if node exists which has an edge to the source node
if (min != 999) { for (i = 0; i < iNo; i++) { // for nodes not included, we proceed
if (include[i] == 0) { // to check if Edge exists between 'i' and 'node'
if (distanceMatrix[i][node] == 999) { //do nothing } else { if ((distance[node] == 999) && (distance[i] == 999)) {//do nothing } else if (distance[i] == 999) // For
inifinity
{ distance[i] = distance[node]
87
+ distanceMatrix[i][node]; path[i] = node; } else if ((distance[node] + distanceMatrix[i][node]) < distance[i]) { distance[i] = distance[node] + distanceMatrix[i][node]; path[i] = node; } } } }//end of for loop } //Checking if all the nodes has been included.
for (i = 0; i < iNo; i++) { iFlag = 1; if (include[i] == 0) { iFlag = 0; break; } } }//end of while (!0) // To generate the output file into 'output.txt
fprintf(fpOutput, ">>>\n"); // Print the distance Array
fprintf(fpOutput, "Distance>"); for (i = 0; i < iNo; i++) fprintf(fpOutput, "%d>", distance[i]); // Print the Path Arrray
fprintf(fpOutput, "\nPath>"); for (i = 0; i < iNo; i++) fprintf(fpOutput, "%d>", path[i] + 1); fclose(fpOutput); /////* User code part end */
}
Create .exe file (Appendix 2: Creating .exe file using Dev C++)
In the left panel, select the Mode as User. Select the .exe file created above.
Select Algorithm as Link State and the remaining input parameters and click Run.
So presently NetSim will run Link State Routing code which is written by the user and will
display the result graphically.
In case of any error, “ERROR IN USER CODE” message will be displayed.
NOTE: Please insert the correct code according to the algorithm selected. The codes for other
algorithm are provided in NetSim Installation CD.
88
Note- How to practice this experiment without using NetSim
Users who do not have a licensed version of NetSim in their PC's, can practice as explained
below.
First, run the exercise in sample mode. The user would see that an Input.txt file is created in
Win OS temp folder (this can be reached by typing %temp%/NetSim in Windows run
window). This input file should be read by the user code and it should generate an Output.txt.
This Output.txt file is read by NetSim and shown graphically to the user.
User can follow the steps provided in Appendix 1: Programming exercise - How to practice
without NetSim.
Given below are sample Input.txt and Output.txt files for this experiment for users to verify
& validate their code.
Input.txt file contents
Algorithm=Link_State
No_of_Router=3
Distance:
999>2>78>
2>999>54>
78>54>999>
Source_Router=1
Destination_Router=3
Output.txt file contents
1>2>3>
1>2>
1>3>
1>
>>>
Distance>0>2>56>
Path>1000>1>2>
*Note- Output.txt content will vary depending on the file contents.
89
11. Congestion Control Algorithm
11.1 Objective:
Study of Network Simulator (NetSim) and simulation of Congestion Control Algorithm
Part A – Network Simulator (NetSim)
11.2 Theory:
What is NetSim?
NetSim is a network simulation tool that allows you to create network scenarios, model
traffic, and study performance metrics.
What is a network?
A network is a set of hardware devices connected together, either physically or logically. This
allows them to exchange information.
A network is a system that provides its users with unique capabilities, above and beyond what
the individual machines and their software applications can provide.
What is simulation?
A simulation is the imitation of the operation of a real-world process or system over time.
Network simulation is a technique where a program models the behavior of a network
either by calculating the interaction between the different network entities (hosts/routers, data
links, packets, etc) using mathematical formulae, or actually capturing and playing back
observations from a production network. The behavior of the network and the various
applications and services it supports can then be observed in a test lab; various attributes of
the environment can also be modified in a controlled manner to assess how the network
would behave under different conditions.
What does NetSim provide?
Simulation: NetSim provides simulation of various protocols working in various networks as
follows: Internetworks, Legacy Networks, BGP Networks, Advanced Wireless
Networks, Cellular Networks, Wireless Sensor Networks, Personal Area Networks,
LTE/LTE-A, IOT(Internet of Things) and Cognitive Radio Networks. Users can open the
90
experiment and save experiments as desired. The different experiments can also be analyzed
using the analytics option in the simulation menu.
Programming: NetSim covers various programming exercises along with concepts,
algorithms, pseudo code and flowcharts. Users can also write their own source codes in
C/C++ and can link them to NetSim.
Some of the programming concepts are Address resolution protocol (ARP), Classless inter
domain routing (CIDR), Cryptography, Distance vector routing, shortest path, Subnetting etc.
Basics: NetSim basics, gives a brief introduction and theoretical knowledge on different
Internetworks, Legacy Networks, BGP Networks, Advanced wireless Networks, Cellular
Networks and devices. Basics also provide more than 200 animations for better
understandability of networking concepts.
help: NetSim help, provides a detail help through user manual and Experiment manual.
Part B – Congestion Control Algorithm
11.3 Theory:
One of the important functions of a TCP Protocol is congestion control in the network. Given
below is a description of how Old Tahoe and Tahoe variants (of TCP) control congestion.
Old Tahoe:
Congestion can occur when data arrives on a big pipe (i.e. a fast LAN) and gets sent out
through a smaller pipe (i.e. a slower WAN). Congestion can also occur when multiple input
streams arrive at a router whose output capacity is less than the sum of the inputs. Congestion
avoidance is a way to deal with lost packets.
The assumption of the algorithm is that the packet loss caused by damaged is very small
(much less than 1%), therefore the loss of a packet signals congestion somewhere in the
network between the source and destination. There are two indications of packets loss: a
timeout occurring and the receipt of duplicate ACKs
91
Congestion avoidance and slow start are independent algorithms with different objectives.
But when congestion occurs TCP must slow down its transmission rate and then invoke slow
start to get things going again. In practice they are implemented together.
Congestion avoidance and slow start requires two variables to be maintained for each
connection: a Congestion Window (i.e. cwnd) and a Slow Start Threshold Size (i.e. ssthresh).
Old Tahoe algorithm is the combination of slow start and congestion avoidance. The
combined algorithm operates as follows,
1. Initialization for a given connection sets cwnd to one segment and ssthresh to 65535
bytes.
2. When congestion occurs (indicated by a timeout or the reception of duplicate ACKs),
one-half of the current window size (the minimum of cwnd and the receiver‟s advertised
window, but at least two segments) is saved in ssthresh. Additionally, if the congestion is
indicated by a timeout, cwnd is set to one segment (i.e. slow start).
3. When new data is acknowledged by the other end, increase cwnd, but the way it increases
depends on whether TCP is performing slow start or congestion avoidance.
If cwnd is less than or equal to ssthresh, TCP is in slow start. Else TCP is performing
congestion avoidance. Slow start continues until TCP is halfway to where it was when
congestion occurred (since it recorded half of the window size that caused the problem in step
2). Then congestion avoidance takes over.
Slow start has cwnd begins at one segment and be incremented by one segment every time an
ACK is received. As mentioned earlier, this opens the window exponentially: send one
segment, then two, then four, and so on. Congestion avoidance dictates that cwnd be
incremented by 1/cwnd, compared to slow start‟s exponential growth. The increase in cwnd
should be at most one segment in each round trip time (regardless of how many ACKs are
received in that RTT), whereas slow start increments cwnd by the number of ACKs received
in a round-trip time.
Tahoe (Fast Retransmit):
The Fast retransmit algorithms operating with Old Tahoe is known as the Tahoe variant.
92
TCP may generate an immediate acknowledgement (a duplicate ACK) when an out-of-order
segment is received out-of-order, and to tell it what sequence number is expected.
Since TCP does not know whether a duplicate ACK is caused by a lost segment or just a re-
ordering of segments, it waits for a small number of duplicate ACKs to be received. It is
assumed that if there is just a reordering of the segments, there will be only one or two
duplicate ACKs before the re-ordered segment is processed, which will then generate a new
ACK. If three or more duplicate ACKs are received in a row, it is a strong indication that a
segment has been lost. TCP then performs a retransmission of what appears to be the missing
segment, without waiting for a re-transmission timer to expire.
11.4 Procedure:
Go to Simulation New Internetworks
Sample Inputs:
Follow the steps given in the different samples to arrive at the objective.
Sample 1.a: Old Tahoe (1 client and 1 server)
In this Sample,
Total no of Node used: 2
Total no of Routers used: 2
The devices are inter connected as given below,
Wired Node C is connected with Router A by Link 1.
Router A and Router B are connected by Link 2.
Wired Node D is connected with Router B by Link 3.
93
Set the properties for each device by following the tables,
Application Properties
Application Type Custom
Source_Id 4(Wired Node D)
Destination_Id 3(Wired Node C)
Packet Size
Distribution Constant
Value (bytes) 1460
Inter Arrival Time
Distribution Constant
Value (micro secs) 1300
Node Properties: In Transport Layer properties, set
TCP Properties
MSS(bytes) 1460
Congestion Control Algorithm Old Tahoe
Window size(MSS) 8
Router Properties: Accept default properties for Router.
Link Properties Link 1 Link 2 Link 3
Max Uplink Speed (Mbps) 8 10 8
Max Downlink Speed(Mbps) 8 10 8
Uplink BER 0.000001 0.000001 0.000001
Downlink BER 0.000001 0.000001 0.000001
94
Simulation Time - 10 Sec
Upon completion of simulation, “Save” the experiment.
(Note: The Simulation Time can be selected only after doing the following two tasks,
Set the properties of Node, Router& Link
Then click on Run Simulation button).
Sample 1.b: Tahoe (1 client and 1 server)
Open sample 1.a, and change the TCP congestion control algorithm to Tahoe (in Node
Properties). Upon completion of simulation, “Save” the experiment as sample 1.b.
Sample 2.a: Old Tahoe (2 clients and 2 servers)
In this Sample,
Total no of Wired Nodes used: 4
Total no of Routers used: 2
The devices are inter connected as given below,
Wired Node A and Wired Node B are connected with Router C by Link 1 and Link 2.
Router C and Router D are connected by Link 3.
Wired Node E and Wired Node F are connected with Router D by Link 4 and Link 5.
Wired Node A and Wired Node B are not transmitting data in this sample.
95
Set the properties for each device by following the tables,
Application Properties Application 1 Application 2
Application Type Custom
Source_Id 5 6
Destination_Id 1 2
Packet Size
Distribution Constant Constant
Value (bytes) 1460 1460
Inter Arrival Time
Distribution Constant Constant
Value (micro secs) 1300 1300
NOTE: The procedure to create multiple applications are as follows:
Step 1: Click on the ADD button present in the bottom left corner to add a new
application.
96
Node Properties: In Transport Layer properties, set
TCP Properties
MSS(bytes) 1460
Congestion Control Algorithm Old Tahoe
Window size(MSS) 8
Router Properties: Accept default properties for Router.
Link Properties Link 1 Link 2 Link 3 Link 4 Link 5
Max Uplink Speed
(Mbps)
8 8 10 8 8
Max Downlink Speed
(Mbps)
8 8 10 8 8
Uplink BER 0.000001 0.000001 0.000001 0.000001 0.000001
Downlink BER 0.000001 0.000001 0.000001 0.000001 0.000001
Simulation Time - 10 Sec
Upon completion of simulation, “Save” the experiment.
(Note: The Simulation Time can be selected only after doing the following two tasks,
Set the properties of Node , Router & Link
Then click on Run Simulation button).
Sample 2.b: Tahoe (2 clients and 2 servers)
Do the experiment as sample 2.a, and change the congestion control algorithm to Tahoe.
Upon completion of simulation, “Save” the experiment.
97
Sample 3.a: Old Tahoe (3 clients and 3 servers)
In this Sample,
Total no of Nodes used: 6
Total no of Routers used: 2
The devices are inter connected as given below,
Wired Node A, Wired Node B & Wired Node C is connected with Router D by Link 1,
Link 2 & Link 3.
Router D and Router E are connected by Link 4.
Wired Node F, Wired Node G & Wired Node H is connected with Router E by Link 5,
Link 6 & Link 7.
Wired Node A, Wired Node B and Wired Node C are not transmitting data in this sample.
Set the properties for each device by following the tables,
Application
Properties
Application 1 Application 2 Application 3
Application Type Custom
Source_Id 6 7 8
Destination_Id 1 2 3
Packet Size
Distribution Constant Constant Constant
Value (bytes) 1460 1460 1460
98
Inter Arrival Time
Distribution Constant Constant Constant
Value (micro sec) 1300 1300 1300
Node Properties: In Transport Layer properties, set
TCP Properties
MSS(bytes) 1460 1460 1460
Congestion Control
Algorithm
Old Tahoe Old Tahoe Old Tahoe
Window size(MSS) 8 8 8
Router Properties: Accept default properties for Router.
Link
Properties
Link 1 Link 2 Link 3 Link 4 Link 5 Link 6 Link 7
Max Uplink
Speed
(Mbps)
8 8 8 10 8 8 8
Max
Downlink
Speed(Mbps)
8 8 8 10 8 8 8
Uplink BER 0.000001 0.000001 0.000001 0.000001 0.000001 0.000001 0.000001
Downlink
BER 0.000001 0.000001 0.000001 0.000001 0.000001 0.000001 0.000001
Simulation Time- 10 Sec
Upon completion of simulation, “Save” the experiment.
(Note: The Simulation Time can be selected only after doing the following two tasks,
Set the properties of Node, Router & Link
Then click on Run Simulation button).
99
Sample 3.b: Tahoe (3 clients and 3 servers)
Do the experiment as sample 3.a, and change the TCP congestion algorithm to Tahoe. Upon
completion of simulation, “Save” the experiment.
11.5 Output
Comparison Table:
TCP
Downloads Metrics
Slow start +
Congestion avoidance
Fast
Retransmit
1 client and 1
server
Throughput(Mbps) 5.926432 6.120320
Segments Retransmitted +
Seg Fast Retransmitted 195 200
2 clients and 2
servers
Throughput(Mbps) 8.796208 8.810224
Segments Retransmitted +
Seg Fast Retransmitted 343 378
3 clients and 3
servers
Throughput(Mbps) 9.144272 9.23304
Segments Retransmitted +
Seg Fast Retransmitted 401 434
Note: To calculate the “Throughput (Mbps)” for more than one application, add the
individual application throughput which is available in Application Metrics (or Metrics.txt) of
Performance Metrics screen. In the same way calculate the metrics for “Segments
Retransmitted + Seg Fast Retransmitted” from TCP Metrics Connection Metrics.
11.6 Inference:
User lever throughput: User lever throughput of Fast Retransmit is higher when compared
then the Old Tahoe (SS + CA). This is because, if a segment is lost due to error, Old Tahoe
waits until the RTO Timer expires to retransmit the lost segment, whereas Tahoe (FR)
retransmits the lost segment immediately after getting three continuous duplicate ACK‟s.
This results in the increased segment transmissions, and therefore throughput is higher in the
case of Tahoe.
100
12. Encryption and Decryption
Objective: Write a C/C++ program to implement Encryption and Decryption using
substitution ciphers
12.1 Theory
A substitution cipher is a method of encryption by which units of plaintext are substituted
with cipher text according to a regular system; the "units" may be single letters (the most
common), pairs of letters. The receiver deciphers the text by performing an inverse
substitution.
Each letter of the plain text is exchanged using another letter according to the key value given
by the user.
The user has to give the message and encrypt that message using the key value. The
encryption is done based on the ASCII value of the alphabetical letter and the key value.
ASCII value of each letter in the plain text is incremented by the key value. The encrypted
text is called as Cipher text.
Example - If the plain text first letter is A, ASCII value of A is 65 and the key value is 1 then
the encrypted value is 65 + 1 = 66, which is B.
Plain text : tetcos Plain text the user wants to encrypt
Key value : 1 The key value by which the plain text is encrypted
Cipher text : ufudpt Cipher text which is encrypted according to the key value.
ASCII value of each letter in the plain text is incremented by 1 (key value) and get the cipher
text.
101
12.2 Algorithm
Read the plain text and key value from the input file.
For i=1 to length (plain text)
i. Get the ascii value of ith
character.
ii. Add the key text to that ascii value.
iii. If the plain text is alphabet then the cipher text should also be alphabet
and vice versa.
iv. The alphabet series for this case is, a, b, c, d...x, y, z, a, b, c, d…
A, B, C, D…X, Y, Z, A, B, C…
v. The user should add key value according to the process to be taken, in
such a way that the series should continue as explained in the previous
point.
12.3 Procedure
To begin with the experiment, open NetSim
Click on Programming from the menu bar, select Cryptography and then select Substitution.
The scenario will be obtained as shown below. Follow the steps.
Step 1:
When you select the User mode, you have to write your own program in C/C++, compile and
link to NetSim software for validation. Click on the F1 (Help) for details on how to proceed
with your own code
Continue with the steps as given for Sample mode.
102
12.4 Results (to be filled up by the students):
Click here to view
concept, algorithm,
pseudo Code &
Flow chart
Click Run to
execute
Enter the Key
text
Enter the plain text
Encryption
Select Mode
Generated Cipher
text
103
Now select Decryption option and then click Run button to get back the original text.
Select Decryption
Click Run
Decrypted original text
104
Step 2:
For user to write their own C Code in NetSim and check the result, click on Interface Source
Code (present in Help in the left pane).
Open Dev C++ or any GNU C compiler based IDK and copy the code from the Interface
Source Code.
For Encryption, the user needs to edit the Interface Source Code at the following location.
void fnSubstutionEncryption() {
// Write your own code here
}
So the user needs to add the user code, create exe and attach it with NetSim to run.
The User code which is to be added is given below
void fnSubstutionEncryption() { /////* User code part start */
// Cipher Text is referenced in szTemp1_Sub_En
szTemp1_Sub_En=szCipher_Sub_En; // Make the Substitution Looping for the string
for(iloop_Sub_En=1;iloop_Sub_En<=(int)strlen(szTmp_Sub_En);iloop_Sub_En++) { // Alphabet Check (UPPER case)
if (((int)(*szPlainTxt_Sub_En) >= 65) && ((int)(*szPlainTxt_Sub_En) <= 90)) { // Get the Ascii value of the character
iTmp_Sub_En = *szPlainTxt_Sub_En; iTmp1_Sub_En = iTmp_Sub_En; // Write the character to the Output file
fprintf(fp_Sub_En,"%c>",iTmp_Sub_En); // Make the Substitution upto iKey_Sub_En times
for(iloop1_Sub_En=1;iloop1_Sub_En<=iKey_Sub_En;iloop1_Sub_En++) { if (iTmp_Sub_En > 90) iTmp_Sub_En = iTmp1_Sub_En + iloop1_Sub_En; else { iTmp_Sub_En = iTmp1_Sub_En + iloop1_Sub_En; if (iTmp_Sub_En == 91) iTmp1_Sub_En = iTmp1_Sub_En - 90 + 64; iTmp_Sub_En = iTmp1_Sub_En + iloop1_Sub_En; } fprintf(fp_Sub_En,"%c>",iTmp_Sub_En); } // Make the character to the Cipher Text
*szCipher_Sub_En=iTmp_Sub_En; fprintf(fp_Sub_En,"\n"); } // Lower Case character
105
else if (((int)(*szPlainTxt_Sub_En) >= 97) && ((int)(*szPlainTxt_Sub_En) <= 122)) { // Get the Ascii value of the character
iTmp_Sub_En = *szPlainTxt_Sub_En; iTmp1_Sub_En = iTmp_Sub_En; // Write the character to the Output file
fprintf(fp_Sub_En,"%c>",iTmp_Sub_En); // Make the Substitution upto iKey_Sub_En times
for(iloop1_Sub_En=1;iloop1_Sub_En<=iKey_Sub_En;iloop1_Sub_En++) { if (iTmp_Sub_En > 122) iTmp_Sub_En = iTmp1_Sub_En + iloop1_Sub_En; else { iTmp_Sub_En = iTmp1_Sub_En + iloop1_Sub_En; if (iTmp_Sub_En == 123) iTmp1_Sub_En = iTmp1_Sub_En - 122 + 96; iTmp_Sub_En = iTmp1_Sub_En + iloop1_Sub_En; } fprintf(fp_Sub_En,"%c>",iTmp_Sub_En); } // Make the character to the Cipher Text
*szCipher_Sub_En=iTmp_Sub_En; fprintf(fp_Sub_En,"\n"); } // Increment the Position of the Cipher Text and the PlainText
szPlainTxt_Sub_En++; szCipher_Sub_En++; } // Final String values szCipher_Sub_En--; *szCipher_Sub_En='\0'; szCipher_Sub_En=szTemp1_Sub_En; fclose(fp_Sub_En); /////* User code part end */
}
Create .exe file (Appendix 2: Creating .exe file using Dev C++)
For Decryption, the user needs to edit the Interface Source Code at the following location.
void fnSubstutionEncryption() {
// Write your own code here
}
So the user needs to add the user code, create exe and attach it with NetSim to run.
The User code which is to be added is given below
void SubstutionDecryption() { /////* User code part start */
szTemp1_Sub_De=szCipher_Sub_De;//Cipher Text is referenced in szTemp1_Sub_De
106
// Make the Substitution Looping for the string for(iloop_Sub_De=1;iloop_Sub_De<=(int)strlen(szTmp_Sub_De);iloop_Sub_De++) { // Alphabet Check (UPPER case)
if (((int)(*szPlainTxt_Sub_De) >= 65) && ((int)(*szPlainTxt_Sub_De) <= 90)) { // Get the Ascii value of the character
iTemp_Sub_De = *szPlainTxt_Sub_De; iTemp1_Sub_De = iTemp_Sub_De; // Write the character to the Output file
fprintf(fp_Sub_De,"%c>",iTemp_Sub_De); // Make the Substitution upto iKey_Sub_De times
for(iloop1_Sub_De=1;iloop1_Sub_De<=iKey_Sub_De;iloop1_Sub_De++) { if (iTemp_Sub_De > 65) iTemp_Sub_De--; else iTemp_Sub_De = 90; fprintf(fp_Sub_De,"%c>",iTemp_Sub_De); } // Make the character to the Cipher Text
*szCipher_Sub_De=iTemp_Sub_De; fprintf(fp_Sub_De,"\n"); } // Lower Case character else if (((int)(*szPlainTxt_Sub_De) >= 97) && ((int)(*szPlainTxt_Sub_De) <= 122)) { // Get the Ascii value of the character iTemp_Sub_De = *szPlainTxt_Sub_De; iTemp1_Sub_De = iTemp_Sub_De; // Write the character to the Output file
fprintf(fp_Sub_De,"%c>",iTemp_Sub_De); // Make the Substitution upto iKey_Sub_De times
for(iloop1_Sub_De=1;iloop1_Sub_De<=iKey_Sub_De;iloop1_Sub_De++) { if (iTemp_Sub_De > 97) iTemp_Sub_De--; else iTemp_Sub_De = 122; fprintf(fp_Sub_De,"%c>",iTemp_Sub_De); } // Make the character to the Cipher Text *szCipher_Sub_De=iTemp_Sub_De; fprintf(fp_Sub_De,"\n"); } else {/*No case*/} // Increment the Position of the Cipher Text and the PlainText szPlainTxt_Sub_De++; szCipher_Sub_De++; } szCipher_Sub_De--; *szCipher_Sub_De='\0'; szCipher_Sub_De=szTemp1_Sub_De; fclose(fp_Sub_De); /////* User code part end */ }
107
In the left panel, select the Mode as User. Select the .exe file created above.
Select Encryption and then provide the Cipher text and Key text. Click Run.
So presently NetSim will run Encryption code which is written by the user and will display
the result graphically.
In case of any error, “ERROR IN USER CODE” message will be displayed.
Perform the similar steps for decryption.
NOTE: Please insert the correct code according to the algorithm selected. The codes for other
algorithm are provided in NetSim Installation CD.
Note- How to practice this experiment without using NetSim
Users who do not have a licensed version of NetSim in their PC's, can practice as explained
below.
First, run the exercise in sample mode. The user would see that an Input.txt file is created in
Win OS temp folder (this can be reached by typing %temp%/NetSim in Windows run
window). This input file should be read by the user code and it should generate an Output.txt.
This Output.txt file is read by NetSim and shown graphically to the user.
User can follow the steps provided in Appendix 1: Programming exercise - How to practice
without NetSim.
Given below are sample Input.txt and Output.txt files for this experiment for users to verify
& validate their code.
Input.txt file contents- For Encryption:
Cryptographic_Technique=Substitution
Cryptographic_Method=Encryption
Plain_Text:
NetSim
Key_Text:
1
108
Output.txt file contents
N>O>
e>f>
t>u>
S>T>
i>j>
m>n>
*Note- Output.txt content will vary depending on the file contents.
Input.txt file contents- For Decryption:
Cryptographic_Technique=Substitution
Cryptographic_Method=Decryption
Cipher_Text:
OfuTjn
Key_Text:
1
Output.txt file contents
O>N>
f>e>
u>t>
T>S>
j>i>
n>m>
*Note- Output.txt content will vary depending on the file contents.
109
Appendix 1: Programming exercise -How to
practice without NetSim
Step 1: Copy Interface Source Code
Click on Interface Source Code and save the code in a text file.
For Example:
As an example, Shortest Path programming
exercise is being considered.
Open the programming exercise and select
Interface Source Code.
Save the Interface source code in another txt
file.
Step 2: Create Input.txt file
Create a new text file with the name Input.txt.
The contents of the file will vary for each programming exercises and are specified in NetSim
User Manual under programming topic.
110
For Example: Copy the input file contents from NetSim user manual and save it in a file
called Input.txt
Sample:
Algorithm=Link_State
No_of_Router=3
Distance:
999>6>5>
6>999>7>
5>7>999>
Source_Router=1
Destination_Router=2
Save it in some other location. In this example, it is saved at D:\New.
Step 3: Create .exe file
Open C editor (Turbo C, Dev C++, etc) and write the Interface source code which was saved
in the first text file. Also add the code to be written by the user in the specific sections and
compile it. Keep the .exe file.
For Example:
Now in C editor (Dev C++ IDE is used here), copy the interface source code. In the interface
source code, void fnDijkstra() is not implemented.
111
After writing the code for the function void fnDijkstra(), create .exe file. The procedure to
create .exe file is explained in Section 9.2 of NetSim User Manual.
In this example, the exe file created is LinkState.exe
Step 4: Run in command prompt
Open command prompt, and go to the folder where the .exe file is saved.
There type
<EXE Name> “<blank>“ “<Path where Input.txt is saved>”;
For Example:
In this example, the exe file LinkState.exe and Input.txt is present at “D:\New”. So in
command prompt go to the folder where exe file is saved.
112
NOTE: For Chat programming exercise (Experiment 6), type
For Sender: <EXE Name> “<blank>“ “<Path where Input.txt is saved>” “send”
For Receiver: <EXE Name> “<blank>“ “<Path where Input.txt is saved>” “receive”
Step 5: Check the output.txt file
After running in the command prompt, Output.txt file will be created at the same location
where Input.txt file is saved. User can compare and check the content of Output.txt file with
the NetSim user manual.
For Example: Here according to this example, the Output.txt file will be created at
“D:\New” folder. User can open the file and compare the content with NetSim user manual
Output.txt content.
113
Appendix 2: Creating .exe file using Dev C++
1. Open the C source code file in Dev C++. Then go to Execute Compile.
Dev C++ will create the exe file in the same location where the C source code file is
located
2. Once exe file is created , link that exe file with NetSim Programming User mode
Note: For Windows 8 and above, use Dev C++ v 5.11
Note: For Windows Vista, set up Dev C++ as shown below
In Dev C++ 4.9.9.2.exe, go to Tools->Compiler Options->Directories tab->Binaries tab
Add the following path as per your installation directory in the text box provided and click on
add button.
C:\Dev-Cpp\libexec\gcc\mingw32\3.4.2
114
In the C Includes tab add the follwing path in the text box provided and click on add button.
C:\Dev-Cpp\lib\gcc\mingw32\3.4.2\include
In the programs tab edit the following paths as shown in screenshot.
115