CN Lab
CN Lab
CN Lab
Experiment 1
AIM: Implement the data link layer framing methods such as character, character-stuffing and
bit stuffing.
Theory: In Data Link layer, the stream of bits from the physical layer is divided into data
frames. The data frames can be of fixed length or variable length. In variable - length framing,
the size of each frame to be transmitted may be different. So, a pattern of bits is used as a
delimiter to mark the end of one frame and the beginning of the next frame. However, if the
pattern occurs in the message, then mechanisms needs to be incorporated so that this situation is
avoided.
The two common approaches are −
Bit - Stuffing − A pattern of bits of arbitrary length is stuffed in the message to
differentiate from the delimiter. This is also called bit - oriented framing.
In a data link frame, the delimiting flag sequence generally contains six or more consecutive 1s.
In order to differentiate the message from the flag in case of the same sequence, a single bit is
stuffed in the message. Whenever a 0 bit is followed by five consecutive 1bits in the message, an
extra 0 bit is stuffed at the end of the five 1s.
When the receiver receives the message, it removes the stuffed 0s after each sequence of five 1s.
The un-stuffed message is then sent to the upper layers.
Byte - Stuffing − A byte is stuffed in the message to differentiate from the delimiter.
This is also called character-oriented framing.
If the pattern of the flag byte is present in the message byte sequence, there should be a strategy
so that the receiver does not consider the pattern as the end of the frame. Here, a special byte
called the escape character (ESC) is stuffed before every byte in the message with the same
pattern as the flag byte. If the ESC sequence is found in the message byte, then another ESC byte
is stuffed before it.
1
Program Code: // BIT Stuffing program
#include<stdio.h>
#include<string.h>
void main()
{
int a[20],b[30],i,j,k,count,n;
printf("Enter frame length:");
scanf("%d",&n);
printf("Enter input frame (0's & 1's only):");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
i=0; count=1; j=0;
while(i<n)
{
if(a[i]==1)
{
b[j]=a[i];
for(k=i+1;a[k]==1 && k<n && count<5;k++)
{
j++;
b[j]=a[k];
count++;
if(count==5)
{
j++;
b[j]=0;
}
i=k;
}}
else
{
b[j]=a[i];
}
i++;
j++;
}
printf("After stuffing the frame is:");
for(i=0;i<j;i++)
printf("%d",b[i]);
}
Output:
Enter frame length:5
Enter input frame (0's & 1's only):
1
1
2
1
1
1
After stuffing the frame is:111110
3
Program Code:
//Program for Character Stuffing
#include<stdio.h>
#include<string.h>
#include<process.h>
void main()
{
int i=0,j=0,n,pos;
char a[20],b[50],ch;
printf("Enter string\n");
scanf("%s",&a);
n=strlen(a);
printf("Enter position\n");
scanf("%d",&pos);
if(pos>n)
{
printf("invalid position, Enter again :");
scanf("%d",&pos);}
printf("Enter the character\n");
ch=getche();
b[0]='d';
b[1]='l';
b[2]='e';
b[3]='s';
b[4]='t';
b[5]='x';
j=6;
while(i<n)
{
if(i==pos-1)
{
b[j]='d';
b[j+1]='l';
b[j+2]='e';
b[j+3]=ch;
b[j+4]='d';
b[j+5]='l';
b[j+6]='e';
j=j+7;
}
if(a[i]=='d' && a[i+1]=='l' && a[i+2]=='e')
{
b[j]='d';
b[j+1]='l';
b[j+2]='e';
4
j=j+3;
}
b[j]=a[i];
i++;
j++;
}
b[j]='d';
b[j+1]='l';
b[j+2]='e';
b[j+3]='e';
b[j+4]='t';
b[j+5]='x';
b[j+6]='\0';
printf("\nframe after stuffing:\n");
printf("%s",b);
}
Enter string
CMRCET
Enter position
2
Enter the character
frame after stuffing:
dlestxCdldleMRCETdleetx
5
Experiment 2
AIM: Write a program to compute CRC code for the polynomials CRC-12, CRC-16 and CRC,
CCIP.
Theory: CRC method can detect a single burst of length n, since only one bit per column will be
changed, a burst of length n+1 will pass undetected, if the first bit is inverted, the last bit is
inverted and all other bits are correct. If the block is badly garbled by a long burst or by multiple
shorter burst, the probability that any of the n columns will have the correct parity that is 0.5. so
the probability of a bad block being expected when it should not be 2 power(-n). This scheme
sometimes is known as Cyclic Redundancy Code.
9 bits (CRC-8)
17 bits (CRC-16)
33 bits (CRC-32)
65 bits (CRC-64)
Algorithm Steps:
Step 1: Declare int crc 16, SHIFT_CRC, shift Byte, Byte_SIZE as global variables.
Step 4: In cal CRC 16 each character from input shifted with shift-byte where value 987.
6
Source Code:
// program for Cyclic Redundancy Check
#include<stdio.h>
int i.data[10].dl.gen[10],gl,temp[10],c;
void left_shift()
for(i=0;i<gl-1;i++)
temp(i)=temp[i+1];
if(c<d1)
temp[gl-1]=data[c];
else
temp[gl-1]=0
void xor()
if(temp[0]==0
left_shift();
c++;
for(i=0;i<gl;i++)
if(gen(i)==temp(i)
temp(i)=0
else
temp[i]=1; } }
7
main()
int j;
printf("1.generate2.check\nchoice:");
scanf("%d",&j);
scanf("%d",&dl);
for(i=0;i<dl;i++)
scanf("%d";&data[i]);
scanf("%d",&gl);
for(i=0;i<gl;i++)
temp[i]=data[i]
if(j==1)
for(c=4;c<dl+gl-2;c++)
{
xor();
printf("crc:");
for(i=0;i<dl;i++)
printf"%d",data[i]);
else
8
{
for(c=4;c<dl;c++)
xor();
left_shift();
printf("crc");
for(i=1;i<gl;i++)
printf("%d"'temp[i]);
printf("\n");
1.generate
2.check
choice:1
Enter the length of data:6
Enter the data:1
0
1
1
0
1
Enter the length of generator:4
Enter the generator:1
1
0
1
crc:101101001
9
Experiment 3
AIM: Develop a simple data link layer that performs the flow control using the sliding window
protocol, and loss recovery using the Go-Back-N mechanism.
Theory: In Go-Back-N ARQ, N is the sender's window size. Suppose we say that Go-
Back-3, which means that the three frames can be sent at a time before expecting the
acknowledgment from the receiver.
It uses the principle of protocol pipelining in which the multiple frames can be sent
before receiving the acknowledgment of the first frame. If we have five frames and the
concept is Go-Back-3, which means that the three frames can be sent, i.e., frame no 1,
frame no 2, frame no 3 can be sent before expecting the acknowledgment of frame no
1.
In Go-Back-N ARQ, the frames are numbered sequentially as Go-Back-N ARQ sends the
multiple frames at a time that requires the numbering approach to distinguish the
frame from another frame, and these numbers are known as the sequential numbers.
The number of frames that can be sent at a time totally depends on the size of the
sender's window. So, we can say that 'N' is the number of frames that can be sent at a
time before receiving the acknowledgment from the receiver.
The sequence number of the outbound frames depends upon the size of the sender's
window. Suppose the sender's window size is 2, and we have ten frames to send, then
the sequence numbers will not be 1,2,3,4,5,6,7,8,9,10. Let's understand through an
example.
The number of bits in the sequence number is 2 to generate the binary sequence
00,01,10,11.
10
Algorithm Steps:
Step 6: Transfer the packet until it reaches the maximum defined size.
Step 7: Resume the window size and repeat the above two steps until packets in.
Source Code:
#include<stdio.h>
int main()
{
int w,i,f,frames[50];
for(i=1;i<=f;i++)
scanf("%d",&frames[i]);
printf("\nWith sliding window protocol the frames will be sent in the following manner
(assuming no corruption of frames)\n\n");
printf("After sending %d frames at each stage sender waits for acknowledgement sent by the
receiver\n\n",w);
for(i=1;i<=f;i++)
11
{
if(i%w==0)
{
printf("%d\n",frames[i]);
printf("Acknowledgement of above frames sent is received by sender\n\n");
}
else
printf("%d ",frames[i]);
}
if(f%w!=0)
printf("\nAcknowledgement of above frames sent is received by sender\n");
return 0;
}
Output
Enter window size: 3
Enter 5 frames: 12 5 89 4 6
With sliding window protocol the frames will be sent in the following manner (assuming no
corruption of frames)
After sending 3 frames at each stage sender waits for acknowledgement sent by the receiver
12 5 89
Acknowledgement of above frames sent is received by sender
46
Acknowledgement of above frames sent is received by sender
12
Experiment 4
AIM: Implement Dijsktra‘s algorithm to compute the shortest path through a network
Theory: Dijkstra‘s algorithm is very similar to Prim‘s algorithm for minimum spanning tree.
Like Prim‘s MST, we generate a SPT (shortest path tree) with given source as root. We
maintain two sets, one set contains vertices included in shortest path tree, other set includes
vertices not yet included in shortest path tree. At every step of the algorithm, we find a vertex
which is in the other set (set of not yet included) and has a minimum distance from the source.
Below are the detailed steps used in Dijkstra‘s algorithm to find the shortest path from a single
source vertex to all other vertices in the given graph.
Algorithm
1) Create a set sptSet (shortest path tree set) that keeps track of vertices included in shortest path
tree, i.e., whose minimum distance from source is calculated and finalized. Initially, this set is
empty.
2) Assign a distance value to all vertices in the input graph. Initialize all distance values as
INFINITE. Assign distance value as 0 for the source vertex so that it is picked first.
3) While sptSet doesn‘t include all vertices
….a) Pick a vertex u which is not there in sptSet and has minimum distance value.
….b) Include u to sptSet.
….c) Update distance value of all adjacent vertices of u. To update the distance values, iterate
through all adjacent vertices. For every adjacent vertex v, if sum of distance value of u (from
source) and weight of edge u-v, is less than the distance value of v, then update the distance
value of v.
SOURCE CODE:
#include<stdio.h>
#include<conio.h>
#define INFINITY 9999
#define MAX 10
void dijkstra(int G[MAX][MAX],int n,int startnode);
int main()
13
{
int G[MAX][MAX],i,j,n,u;
printf("Enter no. of vertices:");
scanf("%d",&n);
printf("\nEnter the adjacency matrix:\n"); for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
printf("\nEnter the starting node:"); scanf("%d",&u);
dijkstra(G,n,u); return 0;
}
void dijkstra(int G[MAX][MAX],int n,int startnode)
{
int cost[MAX][MAX],distance[MAX],pred[MAX]; int
visited[MAX],count,mindistance,nextnode,i,j;
//pred[] stores the predecessor of each node
//count gives the number of nodes seen so far
//create the cost matrix for(i=0;i<n;i++)
for(j=0;j<n;j++) if(G[i][j]==0)
cost[i][j]=INFINITY; else
cost[i][j]=G[i][j];
//initialize pred[],distance[] and visited[] for(i=0;i<n;i++)
{
distance[i]=cost[startnode][i]; pred[i]=startnode; visited[i]=0;
}
distance[startnode]=0; visited[startnode]=1; count=1; while(count<n-1)
{
mindistance=INFINITY;
//nextnode gives the node at minimum distance for(i=0;i<n;i++)
if(distance[i]<mindistance&&!visited[i])
{
mindistance=distance[i]; nextnode=i;
}
//check if a better path exists through nextnode visited[nextnode]=1;
for(i=0;i<n;i++) if(!visited[i])
if(mindistance+cost[nextnode][i]<distance[i])
14
{
distance[i]=mindistance+cost[nextnode][i]; pred[i]=nextnode;
}
count++;
}
//print the path and distance of each node for(i=0;i<n;i++)
if(i!=startnode)
{
printf("\nDistance of node%d=%d",i,distance[i]); printf("\nPath=%d",i);
j=i; do
{
j=pred[j]; printf("<-%d",j);
}while(j!=startnode);
}
}
OUTPUT CONSOLE:
15
Experiment 5
AIM: Take an example subnet of hosts and obtain a broadcast tree for the subnet.
Theory: IP addressing is the allocation of unique ID to each and every system connected in a
network to maintan communication among them through out the affixed network. There are 5
classes of IP Addresses namely A through E with the range varying from one class to the other
class. A subnet is a network allocation to similar systems or same hierarchial systems present in a
allocated network like an organisation. Each and every system can be reachd through a client-
server computing environment where the server acts as the Master and the clients acts as the
Slaves to form a MasterSlave computing environment. Below programs show the calculation of
network addresses with subnet predefinition and subnet generation.
SOURCE CODE:
#include<stdio.h>
int i,j,root;
clrscr();
adj(int k)
int i,j;
printf("Adjacent node of root node::\n"); printf("%d\n",k);
for(j=1;j<=n;j++)
16
{
printf("\n"); for(i=1;i<=n;i++)
}}
OUTPUT:
Enter no.of nodes:5 Enter adjacent matrix
Enter connecting of 1–>1::0 Enter connecting of 1–>2::1 Enter connecting of 1–>3::1 Enter
connecting of 1–>4::0 Enter connecting of 1–>5::0 Enter connecting of 2–>1::1 Enter connecting
of 2–>2::0 Enter connecting of 2–>3::1 Enter connecting of 2–>4::1 Enter connecting of 2–>5::0
Enter connecting of 3–>1::1 Enter connecting of 3–>2::1 Enter connecting of 3–>3::0 Enter
connecting of 3–>4::0 Enter connecting of 3–>5::0 Enter connecting of 4–>1::0 Enter connecting
of 4–>2::1 Enter connecting of 4–>3::0
Enter connecting of 4–>4::0 Enter connecting of 4–>5::1 Enter connecting of 5–>1::0 Enter
connecting of 5–>2::0
Enter connecting of 5–>3::0 Enter connecting of 5–>4::1 Enter connecting of 5–>5::0 Enter root
node:2
Adjacent node of root node:: 2
134
5
17
Experiment 6
AIM: Implement distance vector routing algorithm for obtaining routing tables at each node.
Distance vector routing is an asynchronous algorithm in which node x sends the copy of
its distance vector to all its neighbors. When node x receives the new distance vector
from one of its neighboring vector, v, it saves the distance vector of v and uses the
Bellman-Ford equation to update its own distance vector. The equation is given below:
The node x has updated its own distance vector table by using the above equation and
sends its updated table to all its neighbors so that they can update their own distance
vectors.
1. A router transmits its distance vector to each of its neighbors in a routing packet.
2. Each router receives and saves the most recently received distance vector from each of
its neighbors.
3. A router recalculates its distance vector when:
It receives a distance vector from a neighbor containing different information
than before.
It discovers that a link to a neighbor has gone down.
The DV calculation is based on minimizing the cost to each destination
Dx(y) = Estimate of least cost from x to y
C(x,v) = Node x knows cost to each neighbor v
Dx = [Dx(y): y ∈ N ] = Node x maintains distance vector
Node x also maintains its neighbors' distance vectors
– For each neighbor v, x maintains Dv = [Dv(y): y ∈ N ]
Note –
From time-to-time, each node sends its own distance vector estimate to neighbors.
When a node x receives new DV estimate from any neighbor v, it saves v‘s distance
vector and it updates its own DV using B-F equation:
Dx(y) = min { C(x,v) + Dv(y), Dx(y) } for each node y ∈ N
18
Algorithm
At each node x,
Initialization
Source Code:
#include<stdio.h>
struct node
{
unsigned dist[20]; unsigned from[20];
}rt[10];
int main()
19
{
int dmat[20][20]; int n,i,j,k,count=0;
printf("\nEnter the number of nodes : "); scanf("%d",&n);
printf("\nEnter the cost matrix :\n"); for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
scanf("%d",&dmat[i][j]); dmat[i][i]=0; rt[i].dist[j]=dmat[i][j]; rt[i].from[j]=j;
}
do
{
rt[i].dist[j]=rt[i].dist[k]+rt[k].dist[j]; rt[i].from[j]=k;
count++;
}while(count!=0); for(i=0;i<n;i++)
{
printf("\n\n");
20
OUTPUT CONSOLE:
21
Experiment 7
THEORY:
Data encryption standard was widely adopted by the industry in security products. Plain
text is encrypted in blocks of 64 bits yielding 64 bits of cipher text. The algorithm which is
parameterized by a 56 bit key has 19 distinct stages. The first stage is a key independent
transposition and the last stage is exactly inverse of the transposition. The remaining stages are
functionally identical but are parameterized by different functions of the key. The algorithm has
been designed to allow decryption to be done with the same key as encryption.
Data encryption standard was widely adopted by the industry in security products. Plain text is
encrypted in blocks of 64 bits yielding 64 bits of cipher text. The algorithm which is
parameterized by a 56 bit key has 19 distinct stages. The first stage is a key independent
transposition and the last stage is exactly inverse of the transposition. The remaining stages are
functionally identical but are parameterized by different functions of the key. The algorithm has
been designed to allow decryption to be done with the same key as encryption
SOURCE CODE:
#include<stdio.h> #include<conio.h> #include<string.h>
int p10[]={3,5,2,7,4,10,1,9,8,6},
p8[]={6,3,7,4,8,5,10,9}, p4[]={2,4,3,1};
int ip[]={2,6,3,1,4,8,5,7},
ipinv[]={4,1,3,5,7,2,8,6},
ep[]={4,1,2,3,2,3,4,1};
int s0[][4]={{1,0,3,2,},{3,2,1,0},{0,2,1,3,},{3,1,3,2}};
int s1[][4]={{0,1,2,3},{2,0,1,3},{3,0,1,0},{2,1,0,3}};
void permute(char op[],char ip[],int p[], int n){ int i;
for(i=0;i<n;i++) op[i]=ip[p[i]-1]; op[i]='\0';
}
void circularls(char pr[],int n){ int i;
char ch=pr[0]; for(i=0;i<n-1;i++) pr[i]=pr[i+1]; pr[i]=ch;
}
22
void keygen(char k1[],char k2[],char key[]){ char keytemp[11];
int i;
for(i=0;i<strlen(op)&&i<strlen(ip);i++)
op[i]=(op[i]-'0')^(ip[i]-'0')+'0';
}
void sbox(char op[],char ip[],int s[][4]) { int value;
value=s[(ip[0]-'0')*2+(ip[3]-'0')][(ip[1]-'0')*2+(ip[2]-'0')];
op[0]=value/2+'0'; op[1]=value%2+'0'; op[2]='\0';
}
void fk(char op[],char ip[],char k[])
{
char l[5],r[5],tmp[9],tmp1[9],tmp2[9]; strncpy(l,ip,4);
l[4]='\0';
strncpy(r,ip+4,4); r[4]='\0';
permute(tmp,r,ep,8); xor(tmp,k);
23
char key[11],k1[9],k2[9],plain[9],cipher[9],tmp[9]; clrscr();
printf("enter 10 bit key:"); gets(key);
if(strlen(key)!=10) printf("invalid key length !!"); else
{
keygen(k1,k2,key); printf("sub key k1::"); puts(k1); printf("subkey k2::"); puts(k2);
printf("enter 8 bit plain text:"); gets(plain);
OUTPUT:
24
Experiment 8
AIM: Write a program for congestion control using Leaky bucket algorithm.
Policing: When a packet violates the contract, network can discard or tag the packet giving it
The process of monitoring and enforcing the traffic flow is called policing.
Network monitors traffic flows continuously to ensure they meet their traffic contract.
lower priority Leaky Bucket Algorithm is the most commonly used policing mechanism
If congestion occurs, tagged packets are discarded first
Leaky Bucket Algorithm is the most commonly used policing mechanism
Bucket has specified leak rate for average contracted rate
Bucket has specified depth to accommodate variations in arrival rate
Arriving packet is conforming if it does not result in overflow
Leaky Bucket algorithm can be used to police arrival rate of a packet stream
The above figure shows the leaky bucket algorithm that can be used to police the
At the arrival of the first packet, the content of the bucket is set to zero and the last
Traffic flow. The depth of the bucket is L+I, where l depends on the traffic burstiness.
Conforming time (LCT) is set to the arrival time of the first packet.
At the arrival of the kth packet, the auxiliary variable X‘ records the difference between
the bucket content at the arrival of the last conforming packet and the If the auxiliary variable is
greater than L, the packet is considered as nonconforming,
Inter arrival time between the last conforming packet and the kth packet. Otherwise the
packet is conforming. The bucket content and the arrival time of the packet are then updated.
25
Algorithm:
1. Start
2. Set the bucket size or the buffer size.
3. Set the output rate.
4. Transmit the packets such that there is no overflow.
5. Repeat the process of transmission until all packets are transmitted. (Reject packets where
its size is greater than the bucket size)
6. Stop
26
Source Code:
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
void main()
{
int packets[8],i,j,clk,b_size,o_rate,i_rate,p_sz_rm=0,p_sz,p_time;
clrscr();
for(i=0;i<5;++i)
{
packets[i]=rand()%10; if(packets[i]==0)
--i;
}
printf("Enter output rate:"); scanf("%d",&o_rate); printf("\nEnter bucket size:");
scanf("%d",&b_size); for(i=0;i<5;++i)
{ if((packets[i]+p_sz_rm) > b_size)
{
if(packets[i]>b_size)
printf("\nIncoming packet size:%d greater than bucket capacity\n",packets[i]);
else printf("Bucket size exceeded\n");
}
else
{
p_sz=packets[i]; p_sz_rm+=p_sz;
printf("\n--------------------------------------------------\n");
27
OUTPUT:
28
Experiment 9
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct frame{
int fslno;
char finfo[20];
};
void sort()
{
int i,j,ex;
struct frame temp; for(i=0;i<n;i++)
{
ex=0;
for(j=0;j<n-i-1;j++) if(arr[j].fslno>arr[j+1].fslno)
{
temp=arr[j]; arr[j]=arr[j+1]; arr[j+1]=temp; ex++;
}
if(ex==0) break;
}
}
void main()
{
int i; clrscr();
printf("\n Enter the number of frames \n"); scanf("%d",&n);
for(i=0;i<n;i++)
{
29
arr[i].fslno=random(50);
printf("\n Enter the frame contents for sequence number %d\n",arr[i].fslno);
scanf("%s",arr[i].finfo);
}
sort();
printf("\n The frames in sequence \n"); for(i=0;i<n;i++)
printf("\n %d\t%s \n",arr[i].fslno,arr[i].finfo); getch();
}
OUTPUT
is
30
The frames in sequence
1 bangalore
3 institute
8 technology
14 good
19 a
25 of
28 is
33 very
41 college
31
Experiment 10
AIM: Wireshark i. Packet Capture Using Wire shark ii. Starting Wire shark iii. Viewing
Captured Traffic iv. Analysis and Statistics & Filters.
Wireshark is a network packet analyzer. A network packet analyzer presents captured packet data
in as much detail as possible.
You could think of a network packet analyzer as a measuring device for examining what‘s
happening inside a network cable, just like an electrician uses a voltmeter for examining what‘s
happening inside an electric cable (but at a higher level, of course).
In the past, such tools were either very expensive, proprietary, or both. However, with the advent
of Wireshark, that has changed. Wireshark is available for free, is open source, and is one of the
best packet analyzers available today.
1. Click View > Wireless Toolbar. The Wireless Toolbar will appear just below the Main
toolbar.
2. Use the Wireless Toolbar to configure the desired channel and channel width.
32
3. Under Capture, click on AirPcap USB wireless capture adapter to select the capture
interface.
Note: If the AirPcap isn't listed, press F5 to refresh the list of available packet capture
interfaces.
Note: The AirPcap has been discontinued by RiverBed and is 802.11n only.
33
5. When you are finished capturing, click the Stop button.
Note: .Pcap and .Pcap-ng are good filetypes to use for the capture if you plan to use Eye P.A. to
open the capture.
Start Capturing
The following methods can be used to start capturing packets with Wireshark:
34
You can select an interface in the welcome screen, then select Capture → Start or click
the first toolbar button.
You can get more detailed information about available interfaces using ―The ―Capture
Options‖ Dialog Box‖ (Capture → Options…).
If you already know the name of the capture interface you can start Wireshark from the
command line:
$ wireshark -i eth0 -k
This will start Wireshark capturing on interface eth0. More details can be found at ―Start
Wireshark from the command line‖.
When you open Wireshark without starting a capture or opening a capture file it will display the
―Welcome Screen,‖ which lists any recently opened capture files and available capture interfaces.
Network activity for each interface will be shown in a sparkline next to the interface name. It is
possible to select more than one interface and capture from them simultaneously.
35
Some interfaces allow or require configuration prior to capture. This will be indicated by a
configuration icon ( ) to the left of the interface name. Clicking on the icon will show the
configuration dialog for that interface.
Hovering over an interface will show any associated IPv4 and IPv6 addresses and its capture filter.
Wireshark isn‘t limited to just network interfaces — on most systems you can also capture USB,
Bluetooth, and other types of packets. Note also that an interface might be hidden if it‘s
inaccessible to Wireshark or if it has been hidden as described in ―The ―Manage Interfaces‖ Dialog
Box‖.
When you select Capture → Options… (or use the corresponding item in the main toolbar),
Wireshark pops up the ―Capture Options‖ dialog box as shown in Figure 4.3, ―The ―Capture
Options‖ input tab‖. If you are unsure which options to choose in this dialog box, leaving the
defaults settings as they are should work well in many cases.
The ―Input‖ tab contains the the ―Interface‖ table, which shows the following columns:
Interface
The interface name.
Traffic
A sparkline showing network activity over time.
Link-layer Header
The type of packet captured by this interface. In some cases it is possible to change this.
36
Promiscuous
Lets you put this interface in promiscuous mode while capturing. Note that another
application might override this setting.
Snaplen
The snapshot length, or the number of bytes to capture for each packet. You can set an
explicit length if needed, e.g. for performance or privacy reasons.
Buffer
The size of the kernel buffer that is reserved for capturing packets. You can increase or
decrease this as needed, but the default is usually sufficient.
Monitor Mode
Lets you capture full, raw 802.11 headers. Support depends on the interface type,
hardware, driver, and OS. Note that enabling this might disconnect you from your
wireless network.
Capture Filter
The capture filter applied to this interface. You can edit the filter by double-clicking on it.
Hovering over an interface or expanding it will show any associated IPv4 and IPv6 addresses.
If ―Enable promiscuous mode on all interfaces‖ is enabled, the individual promiscuous mode
settings above will be overridden.
―Capture filter for selected interfaces‖ can be used to set a filter for more than one interface at the
same time.
Manage Interfaces opens the ―The ―Manage Interfaces‖ dialog box‖ where pipes can be defined,
local interfaces scanned or hidden, or remote interfaces added.
Compile Selected BPFs opens ―The ―Compiled Filter Output‖ dialog box‖, which shows you the
compiled bytecode for your capture filter. This can help to better understand the capture filter you
created.
The execution of BPFs can be sped up on Linux by turning on BPF Just In Time compilation by
executing
$ echo 1 >/proc/sys/net/core/bpf_jit_enable
if it is not enabled already. To make the change persistent you can use sysfsutils.
37
The “Capture Options” output tab
Output format
Allows you to set the format of the capture file. pcapng is the default and is more flexible
than pcap. pcapng might be required, e.g. if more than one interface is chosen for
capturing. See https://gitlab.com/wireshark/wireshark/wikis/Development/PcapNg for
more details on pcapng.
Create a new file automatically…
Sets the conditions for switching a new capture file. A new capture file can be created
based on the following conditions:
38
The “Capture Options” options tab
Display Options
Update list of packets in real-time
Updates the packet list pane in real time during capture. If you do not enable this,
Wireshark will not display any packets until you stop the capture. When you check this,
Wireshark captures in a separate process and feeds the captures to the display process.
39
Resolve transport names
Translate transport names (port numbers).
Stop capture automatically after…
You can click Start from any tab to commence the capture or Cancel to apply your changes and
close the dialog.
Once you have captured some packets or you have opened a previously saved capture file, you can
view the packets that are displayed in the packet list pane by simply clicking on a packet in the
packet list pane, which will bring up the selected packet in the tree view and byte view panes.
You can then expand any part of the tree to view detailed information about each protocol in each
packet. Clicking on an item in the tree will highlight the corresponding bytes in the byte view. An
example with a TCP packet selected is shown in ―Wireshark with a TCP packet selected for
viewing‖. It also has the Acknowledgment number in the TCP header selected, which shows up in
the byte view as the selected bytes.
40
You can also select and view packets the same way while Wireshark is capturing if you selected
―Update list of packets in real time‖ in the ―Capture Preferences‖ dialog box.
In addition you can view individual packets in a separate window as shown in ―Viewing a packet
in a separate window‖. You can do this by double-clicking on an item in the packet list or by
selecting the packet in which you are interested in the packet list pane and selecting View → Show
Packet in New Window. This allows you to easily compare two or more packets, even across
multiple files.
41
Along with double-clicking the packet list and using the main menu there are a number of other
ways to open a new packet window:
Under the Statistics menu item, you will find a plethora of options to show details about your
capture.
42
Capture File Properties:
43
Filtering Packets
If you‘re trying to inspect something specific, such as the traffic a program sends when phoning
home, it helps to close down all other applications using the network so you can narrow down
the traffic. Still, you‘ll likely have a large amount of packets to sift through. That‘s where
Wireshark‘s filters come in.
The most basic way to apply a filter is by typing it into the filter box at the top of the window
and clicking Apply (or pressing Enter). For example, type ―dns‖ and you‘ll see only DNS
packets. When you start typing, Wireshark will help you autocomplete your filter.
You can also click Analyze > Display Filters to choose a filter from among the default filters
included in Wireshark. From here, you can add your own custom filters and save them to easily
access them in the future.
44
For more information on Wireshark‘s display filtering language, read the Building display filter
expressions page in the official Wireshark documentation.
Another interesting thing you can do is right-click a packet and select Follow > TCP Stream.
You‘ll see the full TCP conversation between the client and the server. You can also click other
protocols in the Follow menu to see the full conversations for other protocols, if applicable.
Close the window and you‘ll find a filter has been applied automatically. Wireshark is showing
you the packets that make up the conversation.
45
Inspecting Packets
Click a packet to select it and you can dig down to view its details.
You can also create filters from here — just right-click one of the details and use the Apply as
Filter submenu to create a filter based on it.
46
Wireshark is an extremely powerful tool, and this tutorial is just scratching the surface of what
you can do with it. Professionals use it to debug network protocol implementations, examine
security problems and inspect network protocol internals.
47
Experiment 11
Ideally, Nmap should be used as part of an integrated Data Security Platform. Once Nmap has
been used to map a network, a platform such as Varonis‘ Datadvantage can then be used to
implement advanced access control.
How To Use Nmap
Nmap Tutorial and Examples
Nmap Commands
Nmap FAQ
What is Nmap?
At its core, Nmap is a network scanning tool that uses IP packets to identify all the devices
connected to a network and to provide information on the services and operating systems they
are running.
The program is most commonly used via a command-line interface (though GUI front-ends are
also available) and is available for many different operating systems such as Linux, Free BSD,
and Gentoo. Its popularity has also been bolstered by an active and enthusiastic user support
community.
Nmap was developed for enterprise-scale networks and can scan through thousands of connected
devices. However, in recent years Nmap is being increasingly used by smaller companies. The
rise of the IoT, in particular, now means that the networks used by these companies have become
more complex and therefore harder to secure.
This means that Nmap is now used in many website monitoring tools to audit the traffic between
web servers and IoT devices. The recent emergence of IoT botnets, like Mirai, has also
stimulated interest in Nmap, not least because of its ability to interrogate devices connected via
the UPnP protocol and to highlight any devices that may be malicious.
48
What Does Nmap Do?
At a practical level, Nmap is used to provide detailed, real-time information on your networks,
and on the devices connected to them.
The primary uses of Nmap can be broken into three core processes. First, the program gives you
detailed information on every IP active on your networks, and each IP can then be scanned. This
allows administrators to check whether an IP is being used by a legitimate service, or by an
external attacker.
Secondly, Nmap provides information on your network as a whole. It can be used to provide a
list of live hosts and open ports, as well as identifying the OS of every connected device. This
makes it a valuable tool in ongoing system monitoring, as well as a critical part of pentesting.
Nmap can be used alongside the Metasploit framework, for instance, to probe and then repair
network vulnerabilities.
Thirdly, Nmap has also become a valuable tool for users looking to protect personal and business
websites. Using Nmap to scan your own web server, particularly if you are hosting your website
from home, is essentially simulating the process that a hacker would use to attack your site.
―Attacking‖ your own site in this way is a powerful way of identifying security vulnerabilities.
49
How To Use Nmap
Nmap is straightforward to use, and most of the tools it provides are familiar to system admins
from other programs. The advantage of Nmap is that it brings a wide range of these tools into
one program, rather than forcing you to skip between separate and discrete network monitoring
tools.
In order to use Nmap, you need to be familiar with command-line interfaces. Most advanced
users are able to write scripts to automate common tasks, but this is not necessary for basic
network monitoring.
50
How To Run a Ping Scan
One of the most basic functions of Nmap is to identify active hosts on your network. Nmap does
this by using a ping scan. This identifies all of the IP addresses that are currently online without
sending any packers to these hosts.
If you see anything unusual in this list, you can then run a DNS query on a specific host, by
using:
That said, there are advantages to using Kali when running Nmap scans. Most modern distros of
Kali now come with a fully-features Nmap suite, which includes an advanced GUI and results
viewer (Zenmap), a flexible data transfer, redirection, and debugging tool (Ncat), a utility for
comparing scan results (Ndiff), and a packet generation and response analysis tool (Nping).
51
Nmap Commands
Most of the common functions of Nmap can be executed using a single command, and the
program also uses a number of ‗shortcut‘ commands that can be used to automate common tasks.
1. Ping Scanning
As mentioned above, a ping scan returns information on every active IP on your network. You
can execute a ping scan using this command:
1. #
52
2. Port Scanning
There are several ways to execute port scanning using Nmap. The most commonly used are
these:
# sU UDP scans
# sN TCP NULL
The major differences between these types of scans are whether they cover TCP or UDP ports
and whether they execute a TCP connection. Here are the basic differences:
The most basic of these scans is the sS TCP SYN scan, and this gives most users all the
information they need. It scans thousands of ports per second, and because it doesn‘t
complete a TCP connection it does not arouse suspicion.
The main alternative to this type of scan is the TCP Connect scan, which actively queries
each host, and requests a response. This type of scan takes longer than a SYN scan, but can
return more reliable information.
53
The UDP scan works in a similar way to the TCP connect scan but uses UDP packets to
scan DNS, SNMP, and DHCP ports. These are the ports most frequently targeted by
hackers, and so this type of scan is a useful tool for checking for vulnerabilities.
The SCTP INIT scan covers a different set of services: SS7 and SIGTRAN. This type of
scan can also be used to avoid suspicion when scanning an external network because it
doesn‘t complete the full SCTP process.
The TOP NULL scan is also a very crafty scanning technique. It uses a loophole in the
TCP system that can reveal the status of ports without directly querying them, which means
that you can see their status even where they are protected by a firewall.
3. Host Scanning
Host scanning returns more detailed information on a particular host or a range of IP addresses.
As mentioned above, you can perform a host scan using the following command:
4. OS Scanning
OS scanning is one of the most powerful features of Nmap. When using this type of scan, Nmap
sends TCP and UDP packets to a particular port, and then analyze its response. It compares this
response to a database of 2600 operating systems, and return information on the OS (and
version) of a host.
54
5. Scan The Most Popular Ports
If you are running Nmap on a home server, this command is very useful. It automatically scans a
number of the most ‗popular‘ ports for a host. You can run this command using:
6. Output to a File
If you want to output the results of your Nmap scans to a file, you can add an extension to your
commands to do that. Simply add:
-oN output.txt
To your command to output the results to a text file, or:
-oX output.xml
To output to an XML.
55
7. Disable DNS Name Resolution
Finally, you can speed up your Nmap scans by using the -n parameter to disable reverse DNS
resolution. This can be extremely useful if you want to scan a large network. For example, to
turn off DNS resolution for the basic ping scan mentioned above, add -n:
56
Experiment 12
The inner workings of OS detection are quite complex, but it is one of the easiest
features to use. Simply add -O to your scan options. You may want to also increase the
verbosity with -v for even more OS-related details. This is shown in Example 8.1.
Including the -O -v options caused Nmap to generate the following extra line items:
Device type
All fingerprints are classified with one or more high-level device types, such
as router, printer, firewall, or (as in this case) general purpose. These are
further described in the section called ―Device and OS classification
(Class lines)‖. Several device types may be shown, in which case they will be
separated with the pipe symbol as in ―Device Type: router|firewall‖.
57
Running
If Nmap finds too many OS families to print concisely, it will omit this line.
When there are no perfect matches, Nmap changes the field to Running (JUST
GUESSING) and adds an accuracy percentage (100% is a perfect match) in
parentheses after each candidate family name. If no fingerprints are close
matches, the line is omitted.
OS CPE
OS details
This line gives the detailed description for each fingerprint that matches. While
the Device type and Running lines are from predefined enumerated lists that are
easy to parse by a computer, the OS details line contains free-form data which
is useful to a human reading the report. This can include more exact version
numbers, device models, and architectures specific to a given fingerprint. In
this example, the only matching fingerprint was Linux 2.6.20-1 (Fedora Core
5). When there are multiple exact matches, they are comma-separated. If there
aren't any perfect matches, but some close guesses, the field is
renamed Aggressive OS guesses and fingerprints are shown followed by a
percentage in parentheses which specifies how close each match was.
Uptime guess
58
a constant rate such as twice per second. By looking at several responses,
Nmap can determine the current values and rate of increase. Simple linear
extrapolation determines boot time. The timestamp algorithm is used for OS
detection too (see the section called ―TCP timestamp option algorithm (TS)‖)
since the increment rate on different systems varies from 2 Hz to 1,000 Hz.
The uptime guess is labeled a ―guess‖ because various factors can make it
completely inaccurate. Some operating systems do not start the timestamp
counter at zero, but initialize it with a random value, making extrapolation to
zero meaningless. Even on systems using a simple counter starting at zero, the
counter eventually overflows and wraps around. With a 1,000 Hz counter
increment rate, the counter resets to zero roughly every 50 days. So a host that
has been up for 102 days will appear to have been up only two days. Even with
these caveats, the uptime guess is accurate much of the time for most operating
systems, so it is printed when available, but only in verbose mode. The uptime
guess is omitted if the target gives zeros or no timestamp options in its
SYN/ACK packets, or if it does not reply at all. The line is also omitted if
Nmap cannot discern the timestamp increment rate or it seems suspicious (like
a 30-year uptime).
Network Distance
A side effect of one of the OS detection tests allows Nmap to compute how
many routers are between it and a target host. The distance is zero when you
are scanning localhost, and one for a machine on the same network segment.
Each additional router on the path adds one to the hop count. The Network
Distance line is not printed in this example, since Nmap omits the line when it
cannot be computed (no reply to the relevant probe).
Systems with poor TCP initial sequence number generation are vulnerable to
blind TCP spoofing attacks. In other words, you can make a full connection to
those systems and send (but not receive) data while spoofing a different IP
address. The target's logs will show the spoofed IP, and you can take advantage
of any trust relationship between them. This attack was all the rage in the mid-
nineties when people commonly used rlogin to allow logins to their account
without any password from trusted IP addresses. Kevin Mitnick is alleged to
have used this attack to break into Tsutomu Shimomura's computers in
December 1994.
59
The good news is that hardly anyone uses rlogin anymore, and many operating
systems have been fixed to use unpredictable initial sequence numbers as
proposed by RFC 1948. For these reasons, this line is only printed in verbose
mode. Sadly, many vendors still ship vulnerable operating systems and devices.
Even the fixed ones often vary in implementation, which leaves them valuable
for OS detection purposes. The class describes the ISN generation algorithm
used by the target, and difficulty is a rough estimate of how hard the system
makes blind IP spoofing (0 is the easiest). The parenthesized comment is based
on the difficulty index and ranges from Trivial
joke to Easy, Medium, Formidable, Worthy challenge, and finally Good
luck! Further details about sequence tests are provided in the section called
―TCP ISN greatest common divisor (GCD)‖.
While the rlogin family is mostly a relic of the past, clever attackers can still
find effective uses for blind TCP spoofing. For example, it allows for spoofed
HTTP requests. You don't see the results, but just the URL (POST or GET
request) can have dramatic side effects. The spoofing allows attackers to hide
their identity, frame someone else, or exploit IP address restrictions.
IP ID sequence generation
Many systems unwittingly give away sensitive information about their traffic
levels based on how they generate the lowly 16-bit ID field in IP packets. This
can be abused to spoof a port scan against other systems and for other
mischievous purposes discussed in the section called ―TCP Idle Scan (-sI)‖.
This field describes the ID generation algorithm that Nmap was able to discern.
More information on how it classifies them is available in the section called ―IP
ID sequence generation algorithm (TI, CI, II)‖. Note that many systems use a
different IP ID space for each host they communicate with. In that case, they
may appear vulnerable (such as showing the Incremental class) while still
being secure against attacks such as the idle scan. For this reason, and because
the issue is rarely critical, the IP ID sequence generation line is only printed in
verbose mode. If Nmap does not receive sufficient responses during OS
detection, it will omit the whole line. The best way to test whether a host is
vulnerable to being an idle scan zombie is to test it with -sI.
In this example, the line ―No exact OS matches for host‖ means that TCP/IP
fingerprinting failed to find an exact match. Fortunately, the Service Info field a few
lines down discloses that the OS is HP-UX. If several operating systems were detected
(which can happen with NAT gateway boxes that redirect ports to several different
machines), the field would be OSs and the values would be comma separated.
The Service Info line can also contain hostnames and device types found during the
version scan. The focus of this chapter is on TCP/IP fingerprinting though, since
version detection was covered in Chapter 7, Service and Application Version
Detection.
With two effective OS detection methods available, which one should you use? The
best answer is usually both. In some cases, such as a proxy firewall forwarding to an
application on another host, the answers may legitimately differ. TCP/IP
fingerprinting will identify the proxy while version scanning will generally detect the
server running the proxied application. Even when no proxying or port forwarding is
involved, using both techniques is beneficial. If they come out the same, that makes
the results more credible. If they come out wildly different, investigate further to
determine what is going on before relying on either. Since OS and version detection
go together so well, the -A option enables them both.
OS detection is far more effective if at least one open and one closed TCP port are
found. Set the --osscan-limit option and Nmap will not even try OS detection against
hosts which do not meet this criteria. This can save substantial time, particularly on -
61
Pn scans against many hosts. You still need to enable OS detection with -O (or -A) for
the --osscan-limit option to have any effect.
When Nmap performs OS detection against a target and fails to find a perfect match,
it usually repeats the attempt. By default, Nmap tries five times if conditions are
favorable for OS fingerprint submission, and twice when conditions aren't so good.
The --max-os-tries option lets you change this maximum number of OS detection
tries. Lowering it (usually to 1) speeds Nmap up, though you miss out on retries
which could potentially identify the OS. Alternatively, a high value may be set to
allow even more retries when conditions are favorable. This is rarely done, except to
generate better fingerprints for submission and integration into the Nmap OS
database.
Like just about every other part of Nmap, results ultimately come from the target
machine itself. While rare, systems are occasionally configured to confuse or mislead
Nmap. Several programs have even been developed specifically to trick Nmap OS
detection (see the section called ―OS Spoofing‖). Your best bet is to use numerous
reconnaissance methods to explore a network, and don't trust any one of them.
62
Experiment 13
i. NS2 Simulator-Introduction
Introduction to NS-2:
NS2 is an open-source simulation tool that runs on Linux. It is a discreet event
simulator targeted at networking research and provides substantial support for simulation
of routing, multicast protocols and IP protocols, such as UDP, TCP, RTP and SRM over
wired and wireless (local and satellite) networks.
Widely known as NS2, is simply an event driven simulation tool. Useful in
studying the dynamic nature of communication networks.
Simulation of wired as well as wireless network functions and protocols (e.g.,
routing algorithms, TCP, UDP) can be done using NS2.
In general, NS2 provides users with a way of specifying such network protocols and
simulating their corresponding behaviors.
Tcl is a very simple programming language. If you have programmed before, you
can learn enough to write interesting Tcl programs within a few hours. This page provides
a quick overview of the main features of Tcl. After reading this you'll probably be able to
start writing simple Tcl scripts on your own; however, we recommend that you consult one
of the many available Tcl books for more complete information.
63
Basic syntax
This command computes the sum of 20 and 10 and returns the result, 30. You can
try out this example and all the others in this page by typing them to a Tcl application such
as tclsh; after a command completes, tclsh prints its result.
Each Tcl command consists of one or more words separated by spaces. In this
example there are four words: expr, 20, +, and 10. The first word is the name of a command
and the other words are arguments to that command. All Tcl commands consist of words,
but different commands treat their arguments differently. The expr command treats all of its
arguments together as an arithmetic expression, computes the result of that expression, and
returns the result as a string. In the expr command the division into words isn't significant:
you could just as easily have invoked the same command as
expr 20+10
However, for most commands the word structure is important, with each word used
for a distinct purpose.
All Tcl commands return results. If a command has no meaningful result then it
returns an empty string as its result.
Variables
Tcl allows you to store values in variables and use the values later in commands.
The set command is used to write and read variables. For example, the following command
modifies the variable x to hold the value 32:
set x 32
The command returns the new value of the variable. You can read the value of a
variable by invoking set with only a single argument:
set x
You don't need to declare variables in Tcl: a variable is created automatically the
first time it is set. Tcl variables don't have types: any variable can hold any value.
To use the value of a variable in a command, use variable substitution as in
the following example:
expr $x*3
When a $ appears in a command, Tcl treats the letters and digits following it as a
variable name, and substitutes the value of the variable in place of the name. In this
64
example, the actual argument received by the expr command will be 32*3 (assuming that
variable x was set as in the previous example). You can use variable substitution in any
word of any command, or even multiple times within a word:
set cmd
expr set x
11
$cmd $x*$x
Command substitution
You can also use the result of one command in an argument to another command.
This is called command substitution:
set a 44
When a [ appears in a command, Tcl treats everything between it and the matching ]
as a nested Tcl command. Tcl evaluates the nested command and substitutes its result into
the enclosing command in place of the bracketed text. In the example above the second
argument of the second set command will be 176.
Double-quotes allow you to specify words that contain spaces. For example,
consider the following script:
set x 24
set y 18
After these three commands are evaluated variable z will have the value 24 + 18 is 42.
Everything between the quotes is passed to the set command as a single word. Note that (a)
command and variable substitutions are performed on the text between the quotes, and (b)
the quotes themselves are not passed to the command. If the quotes were not present, the set
command would have received 6 arguments, which would have caused an error.
Curly braces provide another way of grouping information into words. They are
different from quotes in that no substitutions are performed on the text between the curly
braces:
set z {$x + $y is [expr $x + $y]}
65
Control structures
return $result
This script consists of a single command, proc. The proc command takes three
arguments: the name of a procedure, a list of argument names, and the body of the
procedure, which is a Tcl script. Note that everything between the curly brace at the end of
the first line and the curly brace on the last line is passed verbatim to proc as a single
argument. The proc command creates a new Tcl command named power that takes two
arguments. You can then invoke power with commands like the following:
power 2 6
power 1.15 5
When power is invoked, the procedure body is evaluated. While the body is
executing it can access its arguments as variables: base will hold the first argument and p
will hold the second.
The body of the power procedure contains three Tcl commands: set, while, and return.
The while command does most of the work of the procedure. It takes two arguments, an
expression ($p > 0) and a body, which is another Tcl script. The while command evaluates its
expression argument using rules similar to those of the C programming language and if the
result is true (nonzero) then it evaluates the body as a Tcl script. It repeats this process over
and over until eventually the expression evaluates to false (zero). In this case the body of
the while command multiplied the result value by base and then decrements p. When p
reaches zero the result contains the desired power of base. The return command causes the
procedure to exit with the value of variable result as the procedure's result.
66
Where do commands come from?
As you have seen, all of the interesting features in Tcl are represented by
commands. Statements are commands, expressions are evaluated by executing commands,
control structures are commands, and procedures are commands.
Tcl commands are created in three ways. One group of commands is provided by
the Tcl interpreter itself. These commands are called builtin commands. They include all of
the commands you have seen so far and many more (see below). The builtin commands are
present in all Tcl applications.
The second group of commands is created using the Tcl extension mechanism. Tcl
provides APIs that allow you to create a new command by writing a command procedure
in C or C++ that implements the command. You then register the command procedure with
the Tcl interpreter by telling Tcl the name of the command that the procedure implements.
In the future, whenever that particular name is used for a Tcl command, Tcl will call your
command procedure to execute the command. The builtin commands are also implemented
using this same extension mechanism; their command procedures are simply part of the Tcl
library.
When Tcl is used inside an application, the application incorporates its key features
into Tcl using the extension mechanism. Thus the set of available Tcl commands varies
from application to application. There are also numerous extension packages that can be
incorporated into any Tcl application. One of the best known extensions is Tk, which
provides powerful facilities for building graphical user interfaces. Other extensions provide
object-oriented programming, database access, more graphical capabilities, and a variety of
other features. One of Tcl's greatest advantages for building integration applications is the
ease with which it can be extended to incorporate new features or communicate with other
resources.
The third group of commands consists of procedures created with the proc
command, such as the power command created above. Typically, extensions are used for
lower-level functions where C programming is convenient, and procedures are used for
higher-level functions where it is easier to write in Tcl.
67
NS Simulator Preliminaries.
Initialization and termination aspects of the ns simulator.
Definition of network nodes, links, queues and topology.
Definition of agents and of applications.
The nam visualization tool.
Tracing and random variables.
Features of NS2
NS2 can be employed in most unix systems and windows. Most of the NS2 code is
in C++. It uses TCL as its scripting language, Otcl adds object orientation to
TCL.NS(version 2) is an object oriented, discrete event driven network simulator that is
freely distributed and open source.
Structure of NS
● NS is an object oriented discrete event simulator
– Simulator maintains list of events and executes one event after another
– Protocols mostly
68
Platforms
It uses TCL as its scripting language OTcl adds object orientation to TCL.
Protocols implemented in NS2
Run simulation
Simulation with NS2
Start the source applications. Packets are then created and are transmitted through
network.
Exit the simulator after a certain fixed time.
NS programming Structure
● Turn on tracing
● Generate traffic
69
● Insert errors
close $nf
exec nam out.nam & exit
0
}
● Start Scheduler
$ns run
Tracing
70
$tcp attach $par
$tcp trace cwnd_
$tcp trace maxseq_
$tcp trace rtt_
Tracing and Animation
[open out.nam w]
$ns namtraceall
$nf
proc finish {} { global ns
nf close $nf
}
Creating topology
[$ns node]
● Create CBR traffic source for feeding into UDP agent set
71
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent$udp0
● FTP
● Telnet
72
ii. Simulate to Find the Number of Packets Dropped
STEPS:
Step1: Select the hub icon on the toolbar and drag it onto the working window.
Step2: Select the host icon on the toolbar and drag it onto the working
window. Repeat this for another host icon.
Step3: Select the link icon on the toolbar and drag it on the screen from host
(node 1) to the hub and again from host(node 2) to the hub. Here the hub acts as
node 3 in the point-to-point network. This leads to the creation of the 3-node
point-to-point network topology. Save this topology as a
.tpl file.
Step4:Double-click on host(node 1), a host dialog box will open up. Click on
Node editor and you can see the different layers- interface, ARP, FIFO, MAC,
TCPDUMP, Physical layers. Select MAC and then select full-duplex for
switches and routers and half duplex for hubs, and in log Statistics, select
Number of Drop Packets, Number of Collisions, Throughput of incoming
packets and Throughput of outgoing packets. Select FIFO and set the queue size
to 50 and press OK. Then click on Add. Another dialog box pops up. Click on
the Command box and type the Command according to the following syntax:
Step 5: Double-click on host (node 2), and follow the same step as above with only
change in command according to the following syntax:
Step 6: Double click on the link between node 1 and the hub to set the bandwidth to some
initial
value say, 10 Mbps. Repeat the same for the other node.
Step 7: Click on the E button (Edit Property) present on the toolbar in order to save the
changes made to the topology. Now click on the R button (RunSimulation). By doing so
73
a user can run/pause/continue/stop/abort/disconnect/reconnect/submit a
simulation. No simulation settings can be changed in this mode.
Step 9:To start the playback, the user can left-click the start icon( |>) of the
time bar located at the bottom. The animation player will then start playing the
recorded packet animation.
Step 10: Change the bandwidth say, 9 Mbps, and run the simulation and compare the two
results.
Note: To get the syntax of any command, double click on the host icon.
Host dialog boxes appear and then choose App. Usage.
74
iii. Simulate to Find the Number of Packets Dropped by TCP/UDP
75
76
77
78
79
80
81
82
83
iv. Simulate to Find the Number of Packets Dropped due to
Congestion
STEPS:
Step 1: Click on the subnet icon on the toolbar and then click
on the screen of the working window.
Step 2:
Selecttherequirednumberofhostsandasuitableradiusbetweent
hehost and the switch.
Step 3: In the edit mode, get the IP address of one of the hosts say,
host 1 and then for the other host say, host2 set the drop
packet and no: of collisions statistics
as described in the earlier experiments.
Step 5: Now click on any one of the hosts and click on command
console and ping the destination node.
ping IP Address of the host
Note: The no: of drop packets are obtained only when the
traffic is more in the network. For checking the no
of packets dropped press ctrl+C
84
v. Simulate to Compare Data Rate& Throughput.
STEPS:
Step 1: Connect one set of hosts with a hub and another set of hosts also
through a hub and connect these two hubs through a switch. This forms an
Ethernet LAN.
stcp [-p
port] [-l
writesize
]
hostIPad
dr rtcp [-
p port] [-
85
l
readsize]
Step 3: Setup the collision log at the destination hosts in the MAC layer as
described in the earlier experiments.
86
vii. Simulate to Determine the Performance with respect to Transmission of Packets
STEPS:
Step 2: Setup multiple mobile nodes around the two WLAN access
points and set the path for each mobile node.
Step 3: Setup a ttcp connection between the mobile nodes and host using the following
command:
Mobile Host 1
ttcp –t –u –s –p 3000 IPAddrOf Receiver
Mobile Host 1
Host(Receiver)
ttcp –r –u –s –p
3000 ttcp –r –u
–s –p 4000
transmission range.
87
88