Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

CNLab Manual

Download as pdf or txt
Download as pdf or txt
You are on page 1of 39

List of Experiments:

1. Study of Network devices in detail and connect the computers in Local Area Network.

Study of Network devices in detail

Definition Network Devices

A computer network’s network devices allow various hardware components to connect. Physical
devices, networking hardware, and network equipment are all terms used to describe these
devices, also known as computer networking devices. Each network device in a computer
network performs a certain function based on its capabilities, so it serves different objectives at
various segments.

Important Network Devices

Hub

Connecting network cables to a connectivity device creates a network segment. A Hub is a name
for this type of communication equipment. In most cases, hubs do not filter data; instead, they
route incoming data frames or packets to any or all of the constituents. Nowadays, all-important
network devices connected to PCs need a central switch or hub.

Repeater

The physical layer could be used to operate a repeater. This device’s primary purpose is to
duplicate the signal on a similar network before it becomes weak or broken. The critical thing to
remember about these gadgets is that they don’t boost the signal. They recreate the signal at its
actual power whenever it becomes weak. A repeater is a gadget with two ports.

Bridge

In a computer network, a bridge connects two or more network segments. A bridge’s primary
function in network design is storing and distributing frames between different components.
Transport frames are connected using (Media Access Control) technology.These can be used to
link two physical local area networks together to form a bigger logical local area network.
Bridges act on the OSI model’s data connection and physical layers to divide large and tiny
networks by managing data flow between networks. Bridges have now been substituted with
switches in recent years to provide more functionality.

NAS (Network-attached storage)

A network-attached storage (NAS) server is a server specialised in filing storage. A NAS


provides a central storage point for a LAN that can be utilised for shared file access and storing
user data backups. NAS devices are a cost-effective and straightforward approach to delivering
network storage. As NASes begin to offer more advanced functionality suitable for small and
mid-sized workplaces, the distinctions between a NAS device and a general-purpose server have
been even more blurred in recent times.

Network Switch

A switch and a hub generally operate at the same LAN layer, but a switch is more intelligent than
a hub. The hub transmits data, but the switch filters and forwards it. As a result, this is the most
creative data packet handling method. When something is received from the switch’s interface, a
data packet can be filtered and forwarded to the indicated receiver’s interface. As a result, a
switch keeps track of system settings in a content addressable memory table, including memory.
The FIB or the forwarding table are other names for this table.

Brouter

The Brouter is also known as a bridging router, and its primary function is to combine the
functions of both a router and just a bridge. It can operate at either the network or data link layer.
When it functions as a router, it routes packets across networks, and then when it functions as a
bridge, it filters LAN traffic.

Gateway

A gateway works at the OSI model’s session and transport layers. TCP/IP and other networking
protocols are transformed through gateways. They’re connected to two or more independent
networks, each with its domain name service, routing algorithm, topology, and network
administration, including policy procedures. Gateways execute all of the functions that routers
do. A gateway is a router that also has the capability of converting traffic. As a result, a protocol
converter is used to switch between network technologies.

Connecting to On-LAN Computers

Access computers on your Local Area Network and provide support and maintenance without
end-user interaction.
1. On the Session Toolbar, click the Computers icon.
2. On the Computers list, click the Connect On LAN tab to see a list of accessible
computers.
3. Filter computers by name or IP address.
Tip: You can search and connect at any time. You do not need to wait for the entire list of
computers to load.
4. Select the computer you want to access and click Connect.
Important: If you do not have Administrator rights, you are prompted to enter the login
credentials of the computer you want to access.

2. Write a Program to implement the data link layer farming methods such as
i) Character stuffing ii) bit stuffing.

Bit Stuffing
Bit stuffing is a technique in which we add extra bits to a given set of data. The added bits don't carry
any information but rather they help in better communication. It is all about protocol management.
Examples:
Input: N = 6, arr[] = {1, 1, 1, 1, 1, 1}
Output: 1111101

Character Stuffing
Character stuffing or Byte Stuffing is the technique of adding a particular byte to the data section
before every byte in the data having the same pattern as the flag.
In Character destuffing while traversing the data we delete the byte with the same pattern as the
given flag and continues traversing the given data frame.

Program:

SOURCE CODE:
// BIT Stuffing program
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
int a[20],b[30],i,j,k,count,n;
clrscr();
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]);
getch();
}
OUTPUT:

NAME OF THE EXPERIMENT: Character Stuffing.


SOURCE CODE:
//PROGRAM FOR CHARACTER STUFFING
#include<stdio.h>

#include<string.h>

main()

char a[30], fs[50] = " ", t[3], sd, ed, x[3], s[3], d[3], y[3];

int i, j, p = 0, q = 0;

clrscr();

printf("Enter characters to be stuffed:");

scanf("%s", a);

printf("\nEnter a character that represents starting delimiter:");

scanf(" %c", &sd);

printf("\nEnter a character that represents ending delimiter:");

scanf(" %c", &ed);

x[0] = s[0] = s[1] = sd;

x[1] = s[2] = '\0';

y[0] = d[0] = d[1] = ed;

d[2] = y[1] = '\0';

strcat(fs, x);

for(i = 0; i < strlen(a); i++)

t[0] = a[i];

t[1] = '\0';

if(t[0] == sd)

strcat(fs, s);

else if(t[0] == ed)


strcat(fs, d);

else

strcat(fs, t);

strcat(fs, y);

printf("\n After stuffing:%s", fs);

getch();

Output:-

Enter characters to be stuffed: goodday

Enter a character that represents starting delimiter: d

Enter a character that represents ending delimiter: g

After stuffing: dggooddddayg.

3. Write a Program to implement data link layer farming method checksum.


#include<stdio.h>
#include<conio.h>
#include<math.h>

int sender(int b[10],int k)


{
int checksum,sum=0,i;
printf("\n****SENDER****\n");

for(i=0;i<k;i++)
sum+=b[i];
printf("SUM IS: %d",sum);

checksum=~sum;
printf("\nSENDER's CHECKSUM IS:%d",checksum);
return checksum;
}

int receiver(int c[10],int k,int scheck)


{
int checksum,sum=0,i;
printf("\n\n****RECEIVER****\n");
for(i=0;i<k;i++)
sum+=c[i];
printf(" RECEIVER SUM IS:%d",sum);
sum=sum+scheck;
checksum=~sum;
printf("\nRECEIVER's CHECKSUM IS:%d",checksum);
return checksum;
}
main()
{
int a[10],i,m,scheck,rcheck;
clrscr();
printf("\nENTER SIZE OF THE STRING:");
scanf("%d",&m);
printf("\nENTER THE ELEMENTS OF THE ARRAY:");
for(i=0;i<m;i++)
scanf("%d",&a[i]);
scheck=sender(a,m);
rcheck=receiver(a,m,scheck);
if(rcheck==0)
printf("\n\nNO ERROR IN TRANSMISSION\n\n");
else
printf("\n\nERROR DETECTED");
getch();
}
4. Write a program for Hamming Code generation for error detection and correction.
#include <stdio.h>
#include <math.h>
int input[32];
int code[32];
int ham_calc(int,int);
void main()
{
int n,i,p_n = 0,c_l,j,k;
printf("Please enter the length of the Data Word: ");
scanf("%d",&n);
printf("Please enter the Data Word:\n");
for(i=0;i<n;i++)
{
scanf("%d",&input[i]);
}

i=0;
while(n>(int)pow(2,i)-(i+1))
{
p_n++;
i++;
}

c_l = p_n + n;

j=k=0;
for(i=0;i<c_l;i++)
{

if(i==((int)pow(2,k)-1))
{
code[i]=0;
k++;
}
else
{
code[i]=input[j];
j++;
}
}
for(i=0;i<p_n;i++)
{
int position = (int)pow(2,i);
int value = ham_calc(position,c_l);
code[position-1]=value;
}
printf("\nThe calculated Code Word is: ");
for(i=0;i<c_l;i++)
printf("%d",code[i]);
printf("\n");
printf("Please enter the received Code Word:\n");
for(i=0;i<c_l;i++)
scanf("%d",&code[i]);

int error_pos = 0;
for(i=0;i<p_n;i++)
{
int position = (int)pow(2,i);
int value = ham_calc(position,c_l);
if(value != 0)
error_pos+=position;
}
if(error_pos == 1)
printf("The received Code Word is correct.\n");
else
printf("Error at bit position: %d\n",error_pos);
}
int ham_calc(int position,int c_l)
{
int count=0,i,j;
i=position-1;
while(i<c_l)
{
for(j=i;j<i+position;j++)
{
if(code[j] == 1)
count++;
}
i=i+2*position;
}
if(count%2 == 0)
return 0;
else
return 1;
}

output:-
Please enter the length of the Data Word: 8
Please enter the Data Word:
1
1
0
1
0
0
1
1
The calculated Code Word is: 011110100011
Please enter the received Code Word:
0
1
1
1
1
1
1
0
0
0
1
1
Error at bit position: 6
--------------------------------
5. Write a Program to implement on a data set of characters the three CRC polynomials – CRC
12, CRC 16 and CRC CCIP.
//Include header files stdio.h, string.h
#define N strlen(g)
char t[28],cs[28],g[28];
int a,e,c,b;
void xor()
{
for(c=1;c<N;c++)
cs[c]=((cs[c]==g[c])?'0':'1');
}
void crc()
{
for(e=0;e<N;e++)
cs[e]=t[e];
do
{
if(cs[0]=='1')
xor();
for(c=0;c<N-1;c++)
cs[c]=cs[c+1];
cs[c]=t[e++];
}while(e<=a+N-1);
}
int main()
{
int flag=0;
do{
printf("\n1.crc12\n2.crc16\ncrc ccit\n4.exit\n\nEnter your option.");
scanf("%d",&b);
switch(b)
{
case 1:strcpy(g,"1100000001111");
break;
case 2:strcpy(g,"11000000000000101");
break;
case 3:strcpy(g,"10001000000100001");
break;
case 4:return 0;
}
printf("\n enter data:");
scanf("%s",t);
printf("\n-----------------------\n");
printf("\n generating polynomial:%s",g);
a=strlen(t);
for(e=a;e<a+N-1;e++)
t[e]='0';
printf("\n--------------------------\n");
printf("mod-ified data is:%s",t);
printf("\n-----------------------\n");
crc();
printf("checksum is:%s",cs);
for(e=a;e<a+N-1;e++)
t[e]=cs[e-a];
printf("\n-----------------------\n");
printf("\n final codeword is : %s",t);
printf("\n------------------------\n");
printf("\ntest error detection 0(yes) 1(no)?:");
scanf("%d",&e);
if(e==0)
{
do{
printf("\n\tenter the position where error is to be inserted:");
scanf("%d",&e);
}
while(e==0||e>a+N-1);
[Type text] [Type text] [Type text]
MVR COLLEGE OF ENGINEERING AND TECHNOLOGY
t[e-1]=(t[e-1]=='0')?'1':'0';
printf("\n-----------------------\n");
printf("\n\terroneous data:%s\n",t);
}
crc();
for(e=0;(e<N-1)&&(cs[e]!='1');e++);
if(e<N-1)
printf("error detected\n\n");
else
printf("\n no error detected \n\n");
printf("\n-----------------------");
}while(flag!=1);
}
crc();
for(e=0;(e<N-1)&&(cs[e]!='1');e++);
if(e<N-1)
printf("error detected\n\n");
else
printf("\n no error detected \n\n");
printf("\n-----------------------");
}while(flag!=1);
Out Put
1.crc12
2.crc16
3.crc ccit
4.exit
Enter your option.1
enter data:1100110011100011
-----------------------
generating polynomial:1100000001111
-------------------------
mod-ified data is:11001100111000110000000000001100000001111
-----------------------
checksum is:1101110110001
-----------------------
final codeword is : 11001100111000111101110110001100000001111
------------------------
test error detection 0(yes) 1(no)?:1
no error detected
-----------------------
1.crc12
2.crc16
3.crc ccit
4.exit

Enter your option.2


enter data:11001100111000
-----------------------
generating polynomial:11000000000000101
--------------------------
mod-ified data is:110011001110000000000000000000000000000000101

6. Write a Program to implement Sliding window protocol for Goback N.


Go Back N protocol in c
code in C:
#include<stdio.h>
int main()
{
int windowsize,sent=0,ack,i;
printf("enter window size\n");
scanf("%d",&windowsize);
while(1)
{
for( i = 0; i < windowsize; i++)
{
printf("Frame %d has been transmitted.\n",sent);
sent++;
if(sent == windowsize)
break;
}
printf("\nPlease enter the last Acknowledgement received.\n");
scanf("%d",&ack);

if(ack == windowsize)
break;
else
sent = ack;
}
return 0;
}
output:-
enter window size
8
Frame 0 has been transmitted.
Frame 1 has been transmitted.
Frame 2 has been transmitted.
Frame 3 has been transmitted.
Frame 4 has been transmitted.
Frame 5 has been transmitted.
Frame 6 has been transmitted.
Frame 7 has been transmitted.

Please enter the last Acknowledgement received.


2
Frame 2 has been transmitted.
Frame 3 has been transmitted.
Frame 4 has been transmitted.
Frame 5 has been transmitted.
Frame 6 has been transmitted.
Frame 7 has been transmitted.

Please enter the last Acknowledgement received.


8
--------------------------------

7. Write a Program to implement Sliding window protocol for Selective repeat.


#include<stdio.h>

int main()
{
int w,i,f,frames[50];

printf("Enter window size: ");


scanf("%d",&w);
printf("\nEnter number of frames to transmit: ");
scanf("%d",&f);

printf("\nEnter %d frames: ",f);

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++)
{
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 number of frames to transmit: 5


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

8. Write a Program to implement Stop and Wait Protocol.


#include <conio.h>
#include <dos.h>
#include <stdio.h>
#include <stdlib.h>
#define TIMEOUT 5
#define MAX_SEQ 1
#define TOT_PACKETS 8
#define inc(k) if(k<MAX_SEQ) k++; else k=0;
typedef struct
{
int data;
}packet;
typedef struct
{
int kind;
int seq;
int ack;
packet info;
int err;
}frame;
frame DATA;
typedef enum{frame_arrival,err,timeout,no_event} event_type;

void from_network_layer(packet *);


void to_network_layer(packet *);
void to_physical_layer(frame *);
void from_physical_layer(frame *);
void wait_for_event_sender(event_type *);
void wait_for_event_reciever(event_type *);
void reciever();
void sender();

int i=1; //Data to be sent by sender


char turn; //r , s
int DISCONNECT=0;
/*__________________________________________________________________________*/
void main()
{
clrscr();
randomize();
while(!DISCONNECT)
{
sender();
delay(400);
reciever();
}
getch();
}
/*__________________________________________________________________________*/
void sender()
{
static int frame_to_send=0;
static frame s;
packet buffer;
event_type event;
static int flag=0;

if(flag==0)
{
from_network_layer(&buffer);
s.info = buffer;
s.seq = frame_to_send;
printf("SENDER : Info = %d Seq No = %d ",s.info,s.seq);
turn = 'r';
to_physical_layer(&s);
flag = 1;
}
wait_for_event_sender(&event);
if(turn=='s')
{
if(event==frame_arrival)
{
from_network_layer(&buffer);
inc(frame_to_send);
s.info = buffer;
s.seq = frame_to_send;
printf("SENDER : Info = %d Seq No = %d ",s.info,s.seq);
turn = 'r';
to_physical_layer(&s);
}
if(event==timeout)
{
printf("SENDER : Resending Frame ");
turn = 'r';
to_physical_layer(&s);
}
}
}
/*__________________________________________________________________________*/
void reciever()
{
static int frame_expected=0;
frame r,s;
event_type event;

wait_for_event_reciever(&event);
if(turn=='r')
{
if(event==frame_arrival)
{
from_physical_layer(&r);
if(r.seq==frame_expected)
{
to_network_layer(&r.info);
inc(frame_expected);
}
else
printf("RECIEVER : Acknowledgement Resent\n");
turn = 's';
to_physical_layer(&s);
}
if(event==err)
{
printf("RECIEVER : Garbled Frame\n");
turn = 's'; //if frame not recieved
} //sender shold send it again
}
}
/*__________________________________________________________________________*/
void from_network_layer(packet *buffer)
{
(*buffer).data = i;
i++;
}
/*___________________________________________________________________________*
/
void to_physical_layer(frame *s)
{ // 0 means error
s->err = random(4); //non zero means no error
DATA = *s; //probability of error = 1/4
}
/*___________________________________________________________________________*
/
void to_network_layer(packet *buffer)
{
printf("RECIEVER :Packet %d recieved , Ack Sent\n",(*buffer).data);
if(i>TOT_PACKETS) //if all packets recieved then disconnect
{
DISCONNECT = 1;
printf("\nDISCONNECTED");
}
}
/*___________________________________________________________________________*
/
void from_physical_layer(frame *buffer)
{
*buffer = DATA;
}
/*___________________________________________________________________________*
/
void wait_for_event_sender(event_type * e)
{
static int timer=0;

if(turn=='s')
{
timer++;
if(timer==TIMEOUT)
{
*e = timeout;
printf("SENDER : Ack not recieved=> TIMEOUT\n");
timer = 0;
return;
}
if(DATA.err==0)
*e = err;
else
{
timer = 0;
*e = frame_arrival;
}
}
}
/*____________________________________________________________________________
*/
void wait_for_event_reciever(event_type * e)
{
if(turn=='r')
{
if(DATA.err==0)
*e = err;
else
*e = frame_arrival;
}

}
9. Write a program for congestion control using leaky bucket algorithm
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>

#define NOF_PACKETS 10

int rand(int a)
{
int rn = (random() % 10) % a;
return rn == 0 ? 1 : rn;
}

int main()
{
int packet_sz[NOF_PACKETS], i, clk, b_size, o_rate, p_sz_rm=0, p_sz, p_time, op;
for(i = 0; i<NOF_PACKETS; ++i)
packet_sz[i] = rand(6) * 10;
for(i = 0; i<NOF_PACKETS; ++i)
printf("\npacket[%d]:%d bytes\t", i, packet_sz[i]);
printf("\nEnter the Output rate:");
scanf("%d", &o_rate);
printf("Enter the Bucket Size:");
scanf("%d", &b_size);
for(i = 0; i<NOF_PACKETS; ++i)
{
if( (packet_sz[i] + p_sz_rm) > b_size)
if(packet_sz[i] > b_size)/*compare the packet siz with bucket size*/
printf("\n\nIncoming packet size (%dbytes) is Greater than bucket capacity
(%dbytes)-PACKET REJECTED", packet_sz[i], b_size);
else
printf("\n\nBucket capacity exceeded-PACKETS REJECTED!!");
else
{
p_sz_rm += packet_sz[i];
printf("\n\nIncoming Packet size: %d", packet_sz[i]);
printf("\nBytes remaining to Transmit: %d", p_sz_rm);
p_time = rand(4) * 10;
printf("\nTime left for transmission: %d units", p_time);
for(clk = 10; clk <= p_time; clk += 10)
{
sleep(1);
if(p_sz_rm)
{
if(p_sz_rm <= o_rate)/*packet size remaining comparing with output rate*/
op = p_sz_rm, p_sz_rm = 0;
else
op = o_rate, p_sz_rm -= o_rate;
printf("\nPacket of size %d Transmitted", op);
printf("----Bytes Remaining to Transmit: %d", p_sz_rm);
}
else
{
printf("\nTime left for transmission: %d units", p_time-clk);
printf("\nNo packets to transmit!!");
}
}
}
}
}
Commands for execution:-

● Open a terminal.
● Change directory to the file location.
● Run gcc filename.c
● If there are no errors, run ./a.out
10. Write a Program to implement Dijkstra‘s algorithm to compute the Shortest path through a
graph.
#include<stdio.h>
#include<conio.h>
#define INFINITY 9999
#define MAX 10

void dijkstra(int G[MAX][MAX],int n,int startnode);

int main()
{
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])
{
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);
}
}

11. Write a Program to implement Distance vector routing algorithm by obtaining routing table
at each node (Take an example subnet graph with weights indicating delay between nodes).
/*
Distance Vector Routing in this program is implemented using Bellman Ford Algorithm:-
*/
#include<stdio.h>
struct node
{
unsigned dist[20];
unsigned from[20];
}rt[10];
int main()
{
int costmat[20][20];
int nodes,i,j,k,count=0;
printf("\nEnter the number of nodes : ");
scanf("%d",&nodes);//Enter the nodes
printf("\nEnter the cost matrix :\n");
for(i=0;i<nodes;i++)
{
for(j=0;j<nodes;j++)
{
scanf("%d",&costmat[i][j]);
costmat[i][i]=0;
rt[i].dist[j]=costmat[i][j];//initialise the distance equal to cost matrix
rt[i].from[j]=j;
}
}
do
{
count=0;
for(i=0;i<nodes;i++)//We choose arbitary vertex k and we calculate the direct distance
from the node i to k using the cost matrix
//and add the distance from k to node j
for(j=0;j<nodes;j++)
for(k=0;k<nodes;k++)
if(rt[i].dist[j]>costmat[i][k]+rt[k].dist[j])
{//We calculate the minimum distance
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<nodes;i++)
{
printf("\n\n For router %d\n",i+1);
for(j=0;j<nodes;j++)
{
printf("\t\nnode %d via %d Distance %d ",j+1,rt[i].from[j]+1,rt[i].dist[j]);
}
}
printf("\n\n");
getch();
}
/*
A sample run of the program works as:-
Enter the number of nodes :
3
Enter the cost matrix :
027
201
710
For router 1
node 1 via 1 Distance 0
node 2 via 2 Distance 2
node 3 via 3 Distance 3
For router 2
node 1 via 1 Distance 2
node 2 via 2 Distance 0
node 3 via 3 Distance 1
For router 3
node 1 via 1 Distance 3
node 2 via 2 Distance 1
node 3 via 3 Distance 0
*/

12. Write a Program to implement Broadcast tree by taking subnet of hosts.


#include<stdio.h>
#include<conio.h>
int p,q,u,v,n;
int min=99,mincost=0;
int t[50][2],i,j;
int parent[50],edge[50][50];
main()
{
clrscr();
printf("\n Enter the number of nodes");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("%c\t",65+i);
parent[i]=-1;
}
printf("\n");
for(i=0;i<n;i++)
{
printf("%c",65+i);
for(j=0;j<n;j++)
scanf("%d",&edge[i][j]);
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
if(edge[i][j]!=99)
if(min>edge[i][j])
{
min=edge[i][j];
u=i;
v=j;
}
p=find(u);
q=find(v);
if(p!=q)
{
t[i][0]=u;
t[i][1]=v;
mincost=mincost+edge[u][v];
sunion(p,q);
}
Else
{
t[i][0]=-1;t[i][1]=-1;
}
min=99;
}
printf("Minimum cost is %d\n Minimum spanning tree is\n" ,mincost);
for(i=0;i<n;i++)
if(t[i][0]!=-1 && t[i][1]!=-1)
{
printf("%c %c %d", 65+t[i][0],65+t[i][1],edge[t[i][0]][t[i][1]]);printf("\n");
}
getch();
}
sunion(int l,int m)
{
parent[l]=m;
}
find(int l)
{
if(parent[l]>0)
i=parent[i];
return i;
}

13. Wireshark i. Packet Capture Using Wire shark ii. Starting Wire shark iii. Viewing Captured
Traffic iv. Analysis and Statistics & Filters.
2.5 Wireshark Fundamentals
Once you’ve successfully installed Wireshark on your system, you can begin to familiarize
yourself with it. Now you finally get to open your fully functioning packet sniffer and see . . .
absolutely nothing!
Okay, so Wireshark isn’t very interesting when you first open it. In order for things to really get
exciting, you need to get some data.
2.6 Your First Packet Capture
To get packet data into Wireshark, you’ll perform your first packet capture. You may be thinking,
“How am I going to capture packets when nothing is wrong on the network?”
First, there is always something wrong on the network. If you don’t believe me, then go ahead
and
send an email to all of your network users and let them know that everything is working
perfectly.
Secondly, there doesn’t need to be something wrong in order for you to perform packet analysis.
In fact, most packet analysts spend more time analyzing problem free traffic than traffic that
theyare troubleshooting. You need a baseline to compare to in order to be able to effectively
troubleshoot network traffic. For example, if you ever hope to solve a problem with DHCP by
analyzing its traffic, you must understand what the flow of working DHCP traffic looks like.
More broadly, in order to find anomalies in daily network activity, you must know what normal
daily network activity looks like. When your network is running smoothly, you can set your
baseline so that you’ll know what its traffic looks like in a normal state.
So, let’s capture some packets!
1. Open Wireshark.
2. From the main drop-down menu, select Capture and then Interfaces. You should see a
dialog listing the various interfaces that can be used to capture packets, along with their IP
addresses.
3. Choose the interface you wish to use, as shown in Figure-3, and click Start, or simply click
the interface under the Interface List section of the welcome page. Data should begin filling
the window.
4. Wait about a minute or so, and when you are ready to stop the capture and view your data,
click the Stop button from the Capture drop-down menu.
Once you have completed these steps and finished the capture process, the Wireshark main
window should be alive with data. As a matter of fact, you might be overwhelmed by the amount
of data that appears, but it will all start to make sense very quickly as we break down the main
window of Wireshark one piece at a time.
2.7 Wireshark’s Main Window
You’ll spend most of your time in the Wireshark main window. This is where all of the packets
you capture are displayed and broken down into a more understandable format. Using the packet
capture you just made, let’s take a look at Wireshark’s main window,
The three panes in the main window depend on one another. In order to view the details of an
individual packet in the Packet Details pane, you must first select that packet by clicking it in the
Packet List pane. Once you’ve selected your packet, you can see the bytes that correspond with a
certain portion of the packet in the Packet Bytes pane when you click that portion of the packet
in
the Packet Details pane.
Here’s what each pane contains:
Packet List: The top pane displays a table containing all packets in the current capture file. It has
columns containing the packet number, the relative time the packet was captured, the source and
destination of the packet, the packet’s protocol, and some general information found in the
packet.
Packet Details: The middle pane contains a hierarchical display of information about a single
packet. This display can be collapsed and expanded to show all of the information collected
about
an individual packet.
Packet Bytes: The lower pane perhaps the most confusing displays a packet in its raw,
unprocessed
form; that is, it shows what the packet looks like as it travels across the wire. This is raw
information with nothing warm or fuzzy to make it easier to follow.
2.8 Wireshark Preferences
Wireshark has several preferences that can be customized to meet your needs. To access
Wireshark’s preferences, select Edit from the main drop-down menu and click Preferences.
You’ll
see the Preferences dialog, which contains several customizable options,
2.9 Packet Color Coding
If you are anything like me, you may enjoy shiny objects and pretty colors. If that is the case,
you
probably got excited when you saw all those different colors in the Packet List pane, as in the
example in Figure-6 (well, the figure is in black and white, but you get the idea). It may seem as
if these colors are randomly assigned to each individual packet, but this is not the case.
As you work with Wireshark on your network, you will begin to notice that you deal with certain
protocols more than others. Here’s where color-coded packets can make your life a lot easier. For
example, if you think that there is a rogue DHCP server on your network handing out IP leases,
you could simply modify the coloring rule for the DHCP protocol so that it shows up in bright
yellow (or some other easily identifiable color). This would allow you to pick out all DHCP
traffic
much more quickly, and make your packet analysis more efficient. These coloring rules can also
be further extended by creating them based on your own custom filters.

14. How to run Nmap scan


Nmap is short for Network Mapper. It is an open-source Linux command-line tool that is used to
scan IP addresses and ports in a network and to detect installed applications.

Nmap allows network admins to find which devices are running on their network, discover open
ports and services, and detect vulnerabilities.
There are a number of reasons why security pros prefer Nmap over other scanning tools.

First, Nmap helps you to quickly map out a network without sophisticated commands or
configurations. It also supports simple commands (for example, to check if a host is up) and
complex scripting through the Nmap scripting engine.

Other features of Nmap include:


Ability to quickly recognize all the devices including servers, routers, switches, mobile devices,
etc on single or multiple networks.
Helps identify services running on a system including web servers, DNS servers, and other
common applications. Nmap can also detect application versions with reasonable accuracy to
help detect existing vulnerabilities.
Nmap can find information about the operating system running on devices. It can provide
detailed information like OS versions, making it easier to plan additional approaches during
penetration testing.
During security auditing and vulnerability scanning, you can use Nmap to attack systems using
existing scripts from the Nmap Scripting Engine.
Nmap has a graphical user interface called Zenmap. It helps you develop visual mappings of a
network for better usability and reporting.
Commands
Let's look at some Nmap commands. If you don't have Nmap installed, you can get it from here.

Basic scans
Scanning the list of active devices on a network is the first step in network mapping. There are
two types of scans you can use for that:

Ping scan — Scans the list of devices up and running on a given subnet.
> nmap -sp 192.168.1.1/24
Scan a single host — Scans a single host for 1000 well-known ports. These ports are the ones
used by popular services like SQL, SNTP, apache, and others.
> nmap scanme.nmap.org
1-3
Stealth scan
Stealth scanning is performed by sending an SYN packet and analyzing the response. If
SYN/ACK is received, it means the port is open, and you can open a TCP connection.

However, a stealth scan never completes the 3-way handshake, which makes it hard for the target
to determine the scanning system.

> nmap -sS scanme.nmap.org


You can use the ‘-sS’ command to perform a stealth scan. Remember, stealth scanning is slower
and not as aggressive as the other types of scanning, so you might have to wait a while to get a
response.

Version scanning
Finding application versions is a crucial part in penetration testing.
It makes your life easier since you can find an existing vulnerability from the Common
Vulnerabilities and Exploits (CVE) database for a particular version of the service. You can then
use it to attack a machine using an exploitation tool like Metasploit.

> nmap -sV scanme.nmap.org


To do a version scan, use the ‘-sV’ command. Nmap will provide a list of services with its
versions. Do keep in mind that version scans are not always 100% accurate, but it does take you
one step closer to successfully getting into a system.

1-5
OS Scanning
In addition to the services and their versions, Nmap can provide information about the
underlying operating system using TCP/IP fingerprinting. Nmap will also try to find the system
uptime during an OS scan.

> nmap -sV scanme.nmap.org


You can use the additional flags like osscan-limit to limit the search to a few expected targets.
Nmap will display the confidence percentage for each OS guess.

Again, OS detection is not always accurate, but it goes a long way towards helping a pen tester
get closer to their target.

1-6
Aggressive Scanning
Nmap has an aggressive mode that enables OS detection, version detection, script scanning, and
traceroute. You can use the -A argument to perform an aggressive scan.

> nmap -A scanme.nmap.org


Aggressive scans provide far better information than regular scans. However, an aggressive scan
also sends out more probes, and it is more likely to be detected during security audits.

1-7
Scanning Multiple Hosts
Nmap has the capability of scanning multiple hosts simultaneously. This feature comes in real
handy when you are managing vast network infrastructure.

You can scan multiple hosts through numerous approaches:

Write all the IP addresses in a single row to scan all of the hosts at the same time.
> nmap 192.164.1.1 192.164.0.2 192.164.0.2
Use the asterisk (*) to scan all of the subnets at once.
> nmap 192.164.1.*
Add commas to separate the addresses endings instead of typing the entire domains.
> nmap 192.164.0.1,2,3,4
Use a hyphen to specify a range of IP addresses
> nmap 192.164.0.0–255
Port Scanning
Port scanning is one of the most fundamental features of Nmap. You can scan for ports in several
ways.

Using the -p param to scan for a single port


> nmap -p 973 192.164.0.1
If you specify the type of port, you can scan for information about a particular type of
connection, for example for a TCP connection.
> nmap -p T:7777, 973 192.164.0.1
A range of ports can be scanned by separating them with a hyphen.
> nmap -p 76–973 192.164.0.1
You can also use the -top-ports flag to specify the top n ports to scan.
> nmap --top-ports 10 scanme.nmap.org
Scanning from a File
If you want to scan a large list of IP addresses, you can do it by importing a file with the list of IP
addresses.

> nmap -iL /input_ips.txt


The above command will produce the scan results of all the given domains in the “input_ips.txt”
file. Other than simply scanning the IP addresses, you can use additional options and flags as
well.

Verbosity and Exporting Scan Results


Penetration testing can last days or even weeks. Exporting Nmap results can be useful to avoid
redundant work and to help with creating final reports. Let’s look at some ways to export Nmap
scan results.

Verbose Output
> nmap -v scanme.nmap.org
The verbose output provides additional information about the scan being performed. It is useful
to monitor step by step actions Nmap performs on a network, especially if you are an outsider
scanning a client’s network.

1-8
Normal output
Nmap scans can also be exported to a text file. It will be slightly different from the original
command line output, but it will capture all the essential scan results.

> nmap -oN output.txt scanme.nmap.org


1-9
XML output
Nmap scans can also be exported to XML. It is also the preferred file format of most pen-testing
tools, making it easily parsable when importing scan results.

> nmap -oX output.xml scanme.nmap.org


1-10
Multiple Formats
You can also export the scan results in all the available formats at once using the -oA command.

> nmap -oA output scanme.nmap.org


The above command will export the scan result in three files — output.xml, output. Nmap and
output.gnmap.

Nmap Help
Nmap has a built-in help command that lists all the flags and options you can use. It is often
handy given the number of command-line arguments Nmap comes with.

> nmap -h
1-12
Nmap Scripting Engine
Nmap Scripting Engine (NSE) is an incredibly powerful tool that you can use to write scripts and
automate numerous networking features.

You can find plenty of scripts distributed across Nmap, or write your own script based on your
requirements. You can even modify existing scripts using the Lua programming language.

1-13
NSE also has attack scripts that are used in attacking the network and various networking
protocols.

Going through the scripting engine in-depth would be out-of-scope for this article, so here is
more information about the Nmap scripting engine.

Zenmap
Zenmap is a graphical user interface for Nmap. It is a free and open-source software that helps
you get up and running with Nmap.

15. Operating System Detection using Nmap

One of Nmap's best-known features is remote OS detection using TCP/IP stack fingerprinting.
Nmap sends a series of TCP and UDP packets to the remote host and examines practically every
bit in the responses. After performing dozens of tests such as TCP ISN sampling, TCP options
support and ordering, IP ID sampling, and the initial window size check, Nmap compares the
results to its nmap-os-db database of more than 2,600 known OS fingerprints and prints out the
OS details if there is a match. Each fingerprint includes a freeform textual description of the OS,
and a classification which provides the vendor name (e.g. Sun), underlying OS (e.g. Solaris), OS
generation (e.g. 10), and device type (general purpose, router, switch, game console, etc). Most
fingerprints also have a Common Platform Enumeration (CPE) representation, like
cpe:/o:linux:linux_kernel:2.6.

If Nmap is unable to guess the OS of a machine, and conditions are good (e.g. at least one open
port and one closed port were found), Nmap will provide a URL you can use to submit the
fingerprint if you know (for sure) the OS running on the machine. By doing this you contribute
to the pool of operating systems known to Nmap and thus it will be more accurate for everyone.

OS detection enables some other tests which make use of information that is gathered during the
process anyway. One of these is TCP Sequence Predictability Classification. This measures
approximately how hard it is to establish a forged TCP connection against the remote host. It is
useful for exploiting source-IP based trust relationships (rlogin, firewall filters, etc) or for hiding
the source of an attack. This sort of spoofing is rarely performed any more, but many machines
are still vulnerable to it. The actual difficulty number is based on statistical sampling and may
fluctuate. It is generally better to use the English classification such as “worthy challenge” or
“trivial joke”. This is only reported in normal output in verbose (-v) mode. When verbose mode
is enabled along with -O, IP ID sequence generation is also reported. Most machines are in the
“incremental” class, which means that they increment the ID field in the IP header for each
packet they send. This makes them vulnerable to several advanced information gathering and
spoofing attacks.

Another bit of extra information enabled by OS detection is a guess at a target's uptime. This
uses the TCP timestamp option (RFC 1323) to guess when a machine was last rebooted. The
guess can be inaccurate due to the timestamp counter not being initialized to zero or the counter
overflowing and wrapping around, so it is printed only in verbose mode.

OS detection is covered in Chapter 8, Remote OS Detection.

OS detection is enabled and controlled with the following options:


-O (Enable OS detection)

Enables OS detection, as discussed above. Alternatively, you can use -A to enable OS detection
along with other things.

--osscan-limit (Limit OS detection to promising targets)

OS detection is far more effective if at least one open and one closed TCP port are found. Set this
option and Nmap will not even try OS detection against hosts that do not meet this criteria. This
can save substantial time, particularly on -Pn scans against many hosts. It only matters when OS
detection is requested with -O or -A.

--osscan-guess; --fuzzy (Guess OS detection results)

When Nmap is unable to detect a perfect OS match, it sometimes offers up near-matches as


possibilities. The match has to be very close for Nmap to do this by default. Either of these
(equivalent) options make Nmap guess more aggressively. Nmap will still tell you when an
imperfect match is printed and display its confidence level (percentage) for each guess.

--max-os-tries (Set the maximum number of OS detection tries against a target)

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. Specifying a lower
--max-os-tries value (such as 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.

16. Do the following using NS2 Simulator i. NS2 Simulator-Introduction ii. Simulate to Find the
Number of Packets Dropped iii. Simulate to Find the Number of Packets Dropped by TCP/UDP
iv. Simulate to Find the Number of Packets Dropped due to Congestion v. Simulate to Compare
Data Rate& Throughput.

1. What is NS2

NS2 stands for Network Simulator Version 2. It is an open-source event-driven simulator


designed specifically for research in computer communication networks.

2. Features of NS2
1. It is a discrete event simulator for networking research.

2. It provides substantial support to simulate bunch of protocols like TCP, FTP, UDP, https and
DSR.

3. It simulates wired and wireless network.

4. It is primarily Unix based.

5. Uses TCL as its scripting language.

6. Otcl: Object oriented support

7. Tclcl: C++ and otcl linkage

8. Discrete event scheduler

3. Basic Architecture

NS2 consists of two key languages: C++ and Object-oriented Tool Command Language (OTcl).
While the C++ defines the internal mechanism (i.e., a backend) of the simulation objects, the
OTcl sets up simulation by assembling and configuring the objects as well as scheduling discrete
events. The C++ and the OTcl are linked together using TclCL

You might also like