Computer Networks Lab Manual

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 98

COMPUTER NETWORKS LABORATORY

MANUAL

III/IV B.Tech, Semester- II


Academic Year: 2023-24

DEPARTMENT OF CSE - (AI & DS)


Prepared by: G DAMODAR

SIR C R REDDY COLLEGE OF ENGINEERING


Eluru-534007, West Godavari Dist, Andhra Pradesh, India
(Accredited by NBA, Approved by AICTE, New Delhi & Permanently affiliated to JNTUK, Kakinada)
Telephone No: 08812-230840, 230565, Fax: 08812-224193
Website: www.sircrrengg.ac.in
SIR C.R.REDDY COLLEGE OF ENGINEERING
ELURU-534007, WEST GODAVARI DIST, A P.,
INDIA
(Approved by AICTE, New Delhi )
Phone no: 08812-230840, 2300656 Fax: 08812-224193
Visit us at http://www.sircrrengg.ac.in
DEPARTMENT OF CSE – (AI & DS)

VISION OF THE DEPARTMENT

To be a premier department in the region with an integrated teaching, learning and


research environment that enables to address the challenges of the core and emerging
technologies with social responsibility.

MISSION OF THE DEPARTMENT

The Mission is to amplify the scholarliness of the students, in theoretical and


practical areas of the discipline integrated with ethical and moral values and
productively apply the same, to invent new and to upgrade the existing technologies
to meet the dynamic needs of the industry with human values.

Mission Elements:
The following mission elements are taken from the mission statement of the
department.
M1: Amplify the scholarliness of the students in theoretical and
practical areas of the discipline.
M2: Application of knowledge gained to invent and develop new products.
M3: Refreshing the existing technologies to meet the dynamic needs
and Challenges of the Industry.
M4: Develop innovative technocrats with ethical and social responsibility.
SIR C.R.REDDY COLLEGE OF ENGINEERING
ELURU-534007, WEST GODAVARI DIST, A P., INDIA
(Approved by AICTE, New Delhi )
Phone no: 08812-230840, 2300656 Fax: 08812-224193
Visit us at http://www.sircrrengg.ac.in
DEPARTMENT OF CSE – (AI & DS)

PROGRAM OUTCOMES (POs)

PO1: Engineering Knowledge: Apply the knowledge of mathematics, science,


engineering fundamentals, and an engineering specialization to the solution of
complex engineering problems.
PO2: Problem Analysis: Identify, formulate, research literature, and analyze
complex engineering problems reaching substantiated conclusions using the first
principles of mathematics, natural sciences, and engineering sciences.
PO3: Design/Development of Solutions: Design solutions for complex engineering
problems and system components or processes that meet the specified needs with
appropriate consideration for the public health and safety, and the cultural, society,
and environmental considerations.
PO4: Conduct Investigations of Complex Problems: Use research-based
knowledge and research methods including design of experiments, analysis and
interpretation of data, and synthesis of the information to provide valid conclusions.
PO5: Modern Tool Usage: Create, select, and apply appropriate techniques,
resources, and modern engineering and IT tools including prediction and modeling to
complex engineering activities with an understanding of the limitations.
PO6: The Engineer and Society: Apply reasoning informed by the contextual
knowledge to assess societal, health, safety, legal and cultural issues and the
consequent responsibilities relevant to the professional engineering practice.
PO7: Environment and Sustainability: Understand the impact of the professional
engineering solutions in society and environmental contexts, and demonstrate the
knowledge of, and need for sustainable development.
PO8: Ethics: Apply ethical principles and commit to professional ethics and
responsibilities and norms of the engineering practice.
PO9: Individual and Team Work: Function effectively as an individual, and as a
member or leader in diverse teams, and in multi-disciplinary settings.
PO10: Communication: Communicate effectively on complex engineering
activities with the engineering community and with society at large, such as, being
able to comprehend and write effective reports and design documentation, make
effective presentations, and give and receive clear instructions.
PO11: Project Management and Finance: Demonstrate knowledge and
understanding of the engineering and management principles and apply these to
one’s own work, as a member and leader in a team, to manage projects and in multi-
disciplinary environments.
PO12: Life-long Learning: Recognize the need for, and have the preparation and
ability to engage in independent and life-long learning in the broadest context of
technological change.
SIR C.R.REDDY COLLEGE OF ENGINEERING
ELURU-534007, WEST GODAVARI DIST, A P., INDIA
(Approved by AICTE, New Delhi )
Phone no: 08812-230840, 2300656 Fax: 08812-224193
Visit us at http://www.sircrrengg.ac.in
DEPARTMENT OF CSE – (AI & DS)

PROGRAM SPECIFIC OUTCOMES (PSOs)

PSO1: Apply Data Science and Machine learning concepts towards development of
Innovative Applications.
PSO2: Apply standard practices and strategies in software project development using
software tools to excel as a professional software developer.

PROGRAM EDUCATIONAL OBJECTIVES (PEOs)

PEO1: To produce graduates with strong foundation of domain knowledge in the


field of Computer Science & Engineering.
PEO2: To produce graduates who can successfully pursue graduate studies and
research in Computer Science& Engineering.

PEO3: To produce graduates who can practice their profession and communicate
effectively either individually or in groups to meet dynamic needs of the industry.
PEO4: To imbibe in graduates a desire for lifelong learning moulded with
professional and ethical values suitable to society.
SIR C.R.REDDY COLLEGE OF ENGINEERING
ELURU-534007, WEST GODAVARI DIST, A P., INDIA
(Approved by AICTE, New Delhi )
Phone no: 08812-230840, 2300656 Fax: 08812-224193
Visit us at http://www.sircrrengg.ac.in
DEPARTMENT OF CSE – (AI & DS)

GENERAL LABORATORY INSTRUCTIONS

1. Students are advised to come to the laboratory at least 5 minutes before (to the starting time),
those who come after 5 minutes will not be allowed into the lab.
2. Plan your task properly much before to the commencement, come prepared to the lab with the
synopsis / program / experiment details.
3. Student should enter into the laboratory with:
a. Laboratory observation notes with all the details (Problem statement, Aim, Algorithm,
Procedure, Program, Expected Output, etc.,) filled in for the lab session.
b. Laboratory Record updated up to the last session experiments and other utensils (if any)
needed in the lab.
c. Proper Dress code and Identity card.
4. Sign in the laboratory login register, write the TIME-IN, and occupy the computer system
allotted to you by the faculty.
5. Execute your task in the laboratory, and record the results / output in the lab observation note
book, and get certified by the concerned faculty.
6. All the students should be polite and cooperative with the laboratory staff, must maintain the
discipline and decency in the laboratory.
7. Computer labs are established with sophisticated and high end branded systems, which should
be utilized properly.
8. Students / Faculty must keep their mobile phones in SWITCHED OFF mode during the lab
sessions. Misuse of the equipment, misbehaviors with the staff and systems etc., will attract severe
punishment.
9. Students must take the permission of the faculty in case of any urgency to go out ; if anybody
found loitering outside the lab / class without permission during working hours will be treated
seriously and punished appropriately.
10. Students should LOG OFF/ SHUT DOWN the computer system before he/she leaves the lab
after completing the task (experiment) in all aspects. He/she must ensure the system / seat is kept
properly.
SIR C.R.REDDY COLLEGE OF ENGINEERING
ELURU-534007, WEST GODAVARI DIST, A P.,
INDIA
(Approved by AICTE, New Delhi )
Phone no: 08812-230840, 2300656 Fax: 08812-224193
Visit us at http://www.sircrrengg.ac.in
DEPARTMENT OF CSE-(AI & DS)

SYLLABUS
List of Experiments:
1. Study of Network devices in detail and connect the computers in Local Area Network.
2. Write a Program to implement the data link layer framing methods such as
i) Character stuffing ii) bit stuffing.
3. Write a Program to implement data link layer framing method checksum.
4. Write a program for Hamming Code generation for error detection and correction.
5. Write a Program to implement on a data set of characters the three CRC polynomials – CRC 12, CRC 16
and CRC CCIP.
6. Write a Program to implement Sliding window protocol for Goback N.
7. Write a Program to implement Sliding window protocol for Selective repeat.
8. Write a Program to implement Stop and Wait Protocol.
9. Write a program for congestion control using leaky bucket algorithm.
10. Write a Program to implement Dijkstra‘s algorithm to compute the Shortest path through a graph.
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).
12. Write a Program to implement Broadcast tree by taking subnet of hosts.
13. Wireshark: (i) Packet Capture Using Wire shark (ii) Starting Wire shark
(iii) Viewing Captured Traffic (iv) Analysis and Statistics & Filters.
14. How to run Nmap scan.
15. Operating System Detection using Nmap.
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.
SIR C.R.REDDY COLLEGE OF ENGINEERING
ELURU-534007, WEST GODAVARI DIST, A P., INDIA
(Approved by AICTE, New Delhi )
Phone no: 08812-230840, 2300656 Fax: 08812-224193
Visit us at http://www.sircrrengg.ac.in
DEPARTMENT OF CSE – (AI & DS)

COURSE OUTCOMES

CO OUTCOMES

1 Apply the basics of Physical layer and transport layer in real time applications.

2 Apply data link layer concepts, design issues, and protocols.

3 Apply Network layer routing protocols and IP addressing.

4 Implement the functions of Application layer and Presentation layer paradigms and Protocols.
SIR C.R.REDDY COLLEGE OF ENGINEERING
ELURU-534007, WEST GODAVARI DIST, A P.,
INDIA
(Approved by AICTE, New Delhi )
Phone no: 08812-230840, 2300656 Fax: 08812-224193
Visit us at http://www.sircrrengg.ac.in
DEPARTMENT OF CSE – (AI & DS)

INDEX
S. No Name of Experiment CO Page No

1 Study of Network devices in detail and connect the 2 12


computers in Local Area Network
2 Implement the data link layer farming methods such as 4 21
character stuffing and bit stuffing
3 Implement data link layer framing method checksum 2 26
Hamming Code generation for error detection and
4 3 30
correction
Implement on a data set of characters the three CRC
5 3 33
polynomials – CRC-12, CRC-16 and CRC-CCIP
6 Implement Sliding window protocol for Goback N 3 37
7 Implement Sliding window protocol for Selective repeat 1 39
8 Implement Stop and Wait Protocol 3 42
9 Congestion control using leaky bucket algorithm 1 46

10 Implement Dijkstra‘s algorithm to compute the Shortest 2 49


path through a graph
Implement Distance vector routing algorithm by
11 obtaining routing table at each node
53
3
12 Implement Broadcast tree by taking subnet of hosts 3 59

13 Introduction to Wireshark 1 63

14 Run the Nmap scan 3 86

15 Operating System Detection using Nmap 1 89

16 Introduction to NS2 Simulator 2 94


EXPERIMENT No: 1

AIM: Study of Network devices in detail and connect the computers in Local Area Network

Procedure: To do this EXPERIMENT- follows these steps:

Hubs:

The hub or network hub connects computers and devices and sends messages and data from any
one device to all the others. If the desktop computer wants to send data to the lapop and it sends
a message to the laptop through the hub, the message will get sent by the hub to all thecomputers
and devices on the network. They need to do work to figure out that the message isnot for them.
The message also uses up bandwidth (room) on the network wires or wireless radiowaves and
limits how much communication can go on. Hubs are not used often these days.

Fig.1 Hub
Switch:

The switch connects the computer network components but it is smart about it. It knows the
address of each item and so when the desktop computer wants to talk to the laptop, it only sends
the message to the laptop and nothing else. In order to have a small home network that just
connects the local equipment all that is really needed is a switch and network cable or the switch
can transmit wireless information that is received by wireless receivers that each of the network
devices have.
Fig. 2 Switch
Bridges:

Bridges are used to divide larger networks into smaller sections. They do this by sitting between
two physical network segments and managing the flow of data between the two. By looking at
the MAC address of the devices connected to each segment, bridges can elect to forward the
data(if they believe that the destination address is on another interface), or block it from crossing
(if they can verify that it is on the interface from which it came).

A bridge functions by blocking or forwarding data, based on the destination MAC address
written into each frame of data. If the bridge believes the destination address is on a network
other than that from which the data was received, it can forward the data to the other networks to
which it is connected. If the address is not on the other side of the bridge, the data is blocked
from passing. Bridges “learn” the MAC addresses of devices on connected networks by
“listening” to network traffic and recording the network from which the traffic originates. Figure
3 shows a representation of a bridge.

Fig 3 Bridges
Routers:

In a common configuration, routers are used to create larger networks by joining two network
segments. A router derives its name from the fact that it can route data it receives from one
network onto another. When a router receives a packet of data, it reads the header of the packetto
determine the destination address. Once it has determined the address, it looks in its routing table
to determine whether it knows how to reach the destination and, if it does, it forwards the packet
to the next hop on the route. The next hop might be the final destination, or it might be another
router. Figure 4 shows, in basic terms, how a router works.

The routing tables play a very important role in the routing process. They are the means bywhich
the router makes its decisions. For this reason, a routing table needs to be two things. It must be
up-to-date, and it must be complete. There are two ways that the router can get the information
for the routing table—through static routing or dynamic routing.

Fig. 4 Router
Gateways:

Any device that translates one data format to another is called a gateway. Some examples of
gateways include a router that translates data from one network protocol to another, a bridge that
converts between two networking systems, and a software application that converts between two
dissimilar formats. The key point about a gateway is that only the data format is translated, not
the data itself. In many cases, the gateway functionality is incorporated into another device.
Fig. 5 Gateways
CSU/DSU:

A Channel Service Unit/Digital Service Unit (CSU/DSU), sometimes called Data Service Unit,
is a device that converts the digital signal format used on LANs into one used on WANs. Such
translation is necessary because the networking technologies used on WANs are different from
those used on LANs. The CSU/DSU sits between the LAN and the access point provided by the
telecommunications company. Many router manufacturers are now incorporating CSU/DSU
functionality into their products.

Network Cards:

Network cards, also called Network Interface Cards, are devices that enable computers
toconnect to the network. When specifying or installing a NIC, you must consider the following
issues:

➤ System bus compatibility—If the network interface you are installing is an internal device,
bus compatibility must be verified. The most common bus system in use is the Peripheral
Component Interconnect (PCI) bus, but some older systems might still use Industry Standard
Architecture (ISA) expansion cards.

➤ System resources—Network cards, like other devices, need IRQ and memory I/O addresses.
If the network card does not operate correctly after installation, there might be a device conflict.

➤ Media compatibility—Today, the assumption is that networks use twisted-pair cabling, so if


you need a card for coaxial or fiber-optic connections, you must specify this. Wireless network
cards are also available.
ISDN Adapters:

Integrated Services Digital Network (ISDN) is a remote access and WAN technology that can
be used in place of a Plain Old Telephone Service (POTS) dial-up link if it is available. The
availability of ISDN depends on whether your local telecommunications service provider offers
the service, the quality of the line to your premises, and your proximity to the provider’s
location. ISDN offers greater speeds than a modem and can also pick up and drop the line
considerably faster. If ISDN is available and you do elect to use it, a special device called an
ISDN terminal adapter is needed to connect to the line.

ISDN terminal adapters can be add-in expansion cards, external devices that connect to the serial
port of the system, or specialized interfaces built in to routers or other networking equipment.
The ISDN terminal adapter is necessary because, although it uses digital signals, the signals are
formatted differently from those used on a LAN. In addition, ISDN can create multiple
communication channels on a single line. Today, ISDN is not widely deployed and has been
replaced by faster and often cheaper technologies.

Wireless Access Points:

Wireless access points (APs) are a transmitter and receiver (transceiver) device used to create a
wireless LAN (WLAN). APs are typically a separate network device with a built-in antenna,
transmitter, and adapter. APs use the wireless infrastructure network mode to provide a
connection point between WLANs and a wired Ethernet LAN. APs also typically have several
ports allowing a way to expand the network to support additional clients.

Modem:

Most everyone wants to connect to the internet. A broadband modem is used to take a high speed
Internet connection provided by an ISP (Internet Service Provider) and convert the data into a
form that your local network can use. The high speed connection can be DSL (Digital
SubscriberLine) from a phone company or cable from a cable television provider.

In order to be reached on the Internet, your computer needs a unique address on the internet.
Your ISP will provide this to you as part of your Internet connection package. This address will
generally not be fixed which means that they may change your address from time to time. For
thevast majority of users, this makes no difference. If you have only one computer and want to
connect to the Internet, you strictly speaking don't need a router. You can plug the network cable
from the modem directly into the network connection of your computer. However, you are much
better off connecting the modem to a router. The ip address your ISP provides will be assigned
tothe router.
Fig. 6 Modem

The router will assign a hidden address (non routable) to each of the computers on the network.
This is strong protection against hackers since they scan ip addresses for computers that are open
to being attacked. The router is not a general purpose computer and will not be visible to them.

Transceivers (Media Converters):

The term transceiver does describe a separate network device, but it can also be technology built
and embedded in devices such as network cards and modems. In a network environment, a
transceiver gets its name from being both a transmitter and a receiver of signals—thus the name
transceivers. Technically, on a LAN, the transceiver is responsible for placing signals onto the
network media and also detecting incoming signals traveling through the same wire. Given the
description of the function of a transceiver, it makes sense that that technology would be found
with network cards. Although transceivers are found in network cards, they can be external
devices as well.

As far as networking is concerned, transceivers can ship as a module or chip type. Chip
transceivers are small and are inserted into a system board or wired directly on a circuit board.
Module transceivers are external to the network and are installed and function similarly to other
computer peripherals, or they can function as standalone devices.

Firewalls:

A firewall is a networking device, either hardware or software based, that controls access to your
organization’s network. This controlled access is designed to protect data and resources from an
outside threat. To do this, firewalls are typically placed at entry/exit points of a network—for
example, placing a firewall between an internal network and the Internet. Once there, it can
control access in and out of that point.

Although firewalls typically protect internal networks from public networks, they are also used
to control access between specific network segments within a network—for example, placing a
firewall between the Accounts and the Sales departments.

Fig. 7 Firewall
MAC Addresses:

A MAC address is a unique 6-byte address that is burned into each network interface or more
specifically, directly into the PROM chip on the NIC. The number must be unique, as the MAC
address is the basis by which almost all network communication takes place. No matter which
networking protocol is being used, the MAC address is still the means by which the network
interface is identified on the network. Notice that I say network interface. That’s very
important, as a system that has more than one network card in it will have more than one MAC
address.

MAC addresses are expressed in six hexadecimal values. In some instances, the six values are
separated by colons (:); in others, hyphens (-) are used; and in still others, a space is simply
inserted between the values. In any case, because the six values are hexadecimal, they can only
be numbers 0–9 and the letters A–F
Connect the computers in Local Area Network.

Procedure: On the host computer

On the host computer, follow these steps to share the Internet connection:

1. Log on to the host computer as Administrator or as Owner.


2. Click Start, and then click Control Panel.
3. Click Network and Internet Connections.
4. Click Network Connections.
5. Right-click the connection that you use to connect to the Internet. For example,
if you connect to the Internet by using a modem, right-click the connection that
you want under Dial-up / other network available.
6. Click Properties.
7. Click the Advanced tab.

8. Under Internet Connection Sharing, select the Allow other network users to
connect through this computer's Internet connection check box.

9. If you are sharing a dial-up Internet connection, select the Establish a dial-up
connectionwhenever a computer on my network attempts to access the Internet
check box if you want to permit your computer to automatically connect to the
Internet.

10. Click OK. You receive the following message:

When Internet Connection Sharing is enabled, your LAN adapter will be set to use
IP address192.168.0.1. Your computer may lose connectivity with other computers
on your network. Ifthese other computers have static IP addresses, it is a good idea
to set them to obtain their IP addresses automatically. Are you sure you want to
enable Internet Connection Sharing?

11. Click Yes.


The connection to the Internet is shared to other computers on the local area network (LAN).

The network adapter that is connected to the LAN is configured with a static IP
address of 192.168.0.1 and a subnet mask of 255.255.255.0

On the client computer

To connect to the Internet by using the shared connection, you must confirm the
LAN adapterIP configuration, and then configure the client computer. To confirm
the LAN adapter IP configuration, follow these steps:

1. Log on to the client computer as Administrator or as Owner.


2. Click Start, and then click Control Panel.
3. Click Network and Internet Connections.
4. Click Network Connections.
5. Right-click Local Area Connection and then click Properties.
6. Click the General tab, click Internet Protocol (TCP/IP) in the connection uses thefollowing
items list, and then click Properties.

7. In the Internet Protocol (TCP/IP) Properties dialog box, click Obtain an IP addressautomatically
(if it is not already selected), and then click OK.

Note: You can also assign a unique static IP address in the range of 192.168.0.2 to 192.168.0.254. For
example, you can assign the following static IP address, subnet mask, anddefault gateway:

8. IP Address 192.168.31.202
9. Subnet mask 255.255.255.0
10. Default gateway 192.168.31.1

11. In the Local Area Connection Properties dialog box, click OK.

12. Quit Control Panel.


EXPERIMENT No: 2

AIM: Implement the data link layer framing methods such as character stuffing and bit
stuffing.
SOURCE CODE:
Character stuffing :
include<stdio.h>
#include<string.h>
int 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;
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);
return 0;
}

Output:
[cs228@rhel4server ~]$ vi cn.c
[cs228@rhel4server ~]$ gcc cn.c
[cs228@rhel4server ~]$ ./a.out
Enter characters to be stuffed:crrcse-asection
Enter a character that represents starting delimiter:a
Enter a character that represents ending delimiter:n
After stuffing: acrrcse-aasectionnn
[cs228@rhel4server ~]$

Bit stuffing:
#include<stdio.h>
#include<string.h>
int main()
{
int a[20],b[30],i,j,k,count,n;
printf("Enter frame size (Example: 8):");
scanf("%d",&n);
printf("Enter the frame in the form of 0 and 1 :");
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 Bit Stuffing :");
for(i=0; i<j; i++)
printf("%d",b[i]);
return 0;
}

Output:
[cs228@rhel4server ~]$ gcc bitstuffing.c
[cs228@rhel4server ~]$ ./a.out
Enter frame size (Example: 8):12
Enter the frame in the form of 0 and 1 :0 1 1 1 1 1 1 0 0 0 0 0
After Bit Stuffing :0111110100000
[cs228@rhel4server ~]$
EXPERIMENT No: 3

AIM: Implement data link layer framing method checksum

Source code:
#include<stdio.h>
#include<string.h>

int main()
{
char a[20],b[20];
char sum[20],complement[20];
int i,length;

printf("Enter first binary string\n");


scanf("%s",&a);
printf("Enter second binary string\n");
scanf("%s",&b);

if(strlen(a)==strlen(b)){
length = strlen(a);
char carry='0';

for(i=length-1;i>=0;i--)
{
if(a[i]=='0' && b[i]=='0' && carry=='0')
{
sum[i]='0';
carry='0';
}
else if(a[i]=='0' && b[i]=='0' && carry=='1')
{
sum[i]='1';
carry='0';

}
else if(a[i]=='0' && b[i]=='1' && carry=='0')
{
sum[i]='1';
carry='0';

}
else if(a[i]=='0' && b[i]=='1' && carry=='1')
{
sum[i]='0';
carry='1';

}
else if(a[i]=='1' && b[i]=='0' && carry=='0')
{
sum[i]='1';
carry='0';

}
else if(a[i]=='1' && b[i]=='0' && carry=='1')
{
sum[i]='0';
carry='1';

}
else if(a[i]=='1' && b[i]=='1' && carry=='0')
{
sum[i]='0';
carry='1';

}
else if(a[i]=='1' && b[i]=='1' && carry=='1')
{
sum[i]='1';
carry='1';

}
else
break;
}

printf("\nSum=%c%s",carry,sum);
for(i=0;i<length;i++)
{
if(sum[i]=='0')
complement[i]='1';
else
complement[i]='0';
}

if(carry=='1')
carry='0';
else
carry='1';

printf("\nChecksum=%c%s",carry,complement);
}
else {
printf("\nWrong input strings");
}
}
EXPERIMENT No: 4

AIM: Hamming Code generation for error detection and correction


Source code:
#include<stdio.h>

void main()
{ int
data[10];
int dataatrec[10],c,c1,c2,c3,i;

printf("Enter 4 bits of data one by one\n");


scanf("%d",&data[0]);
scanf("%d",&data[1]);

scanf("%d",&data[2]);

scanf("%d",&data[4]);

//Calculation of even parity


data[6]=data[0]^data[2]^data[4];
data[5]=data[0]^data[1]^data[4];
data[3]=data[0]^data[1]^data[2];

printf("\nEncoded data is\n");


for(i=0;i<7;i++)
printf("%d",data[i]);

printf("\n\nEnter received data bits one by one\n");


for(i=0;i<7;i++)
scanf("%d",&dataatrec[i]);

c1=dataatrec[6]^dataatrec[4]^dataatrec[2]^dataatrec[0];
c2=dataatrec[5]^dataatrec[4]^dataatrec[1]^dataatrec[0];
c3=dataatrec[3]^dataatrec[2]^dataatrec[1]^dataatrec[0];
c=c3*4+c2*2+c1 ;

if(c==0) {
printf("\nNo error while transmission of data\n");
}
else {
printf("\nError on position %d",c);

printf("\nData sent : ");


for(i=0;i<7;i++)
printf("%d",data[i]);

printf("\nData received : ");


for(i=0;i<7;i++)
printf("%d",dataatrec[i]);
printf("\nCorrect message is\n");
//if errorneous bit is 0 we complement it else vice versa
if(dataatrec[7-c]==0)
dataatrec[7-c]=1;
else
dataatrec[7-c]=0;
for (i=0;i<7;i++) {
printf("%d",dataatrec[i]);
}
}
}

Output:

Enter 4 bits of data one by one


1
0
1
0

Encoded data is
1010010

Enter received data bits one by one


1
0
1
0
0
1
0

No error while transmission of data


EXPERIMENT No: 5

AIM: Implement on a data set of characters the three CRC polynomials – CRC-12, CRC-16 and CRC-CCIP
Source code:
#include<stdio.h>
int gen[4],genl,frl,rem[4];
int main()
{
int i,j,fr[8],dupfr[11],recfr[11],tlen,flag;
frl=8;
genl=4;
printf("enter frame:");
for(i=0;i<frl;i++)
{
scanf("%d",&fr[i]);
dupfr[i]=fr[i];
}
printf("enter generator:");
for(i=0;i<genl;i++)
scanf("%d",&gen[i]);
tlen=frl+genl-1;
for(i=frl;i<tlen;i++)
{
dupfr[i]=0;
}
reminder(dupfr);
for(i=0;i<frl;i++)
{
recfr[i]=fr[i];
}
for(i=frl,j=1;j<genl;i++,j++)
{
recfr[i]=rem[j];
}
reminder(recfr);
flag=0;
for(i=0;i<4;i++)
{
if(rem[i]!=0)
flag++;
}
if(flag==0)
{
printf("frame received correctly");
}
else
{
printf("the received frame is wrong");
}
}
reminder(int fr[])
{
int k,k1,i,j;
for(k=0;k<frl;k++)
{
if(fr[k]==1)
{
k1=k; for(i=0,j=k;i<genl;i++,j+
+)
{
rem[i]=fr[j]^gen[i];
}
for(i=0;i<genl;i++)
{
fr[k1]=rem[i];
k1++;
}
}
}
return 0;
}

output:
dear students all of enter 8 digits as frame and generator as 4 digits
[cs228@rhel4server ~]$ vi crc.c
[cs228@rhel4server ~]$ gcc crc.c
[cs228@rhel4server ~]$ ./a.out
enter frame:1 1 1 1 1 1 1 1
enter generator:1 1 0 1
frame received correctly
[cs228@rhel4server ~]
[cs228@rhel4server ~]$ ./a.out
enter frame:1 1 1 1 1 0 0 0
enter generator:1 1 1 1
the received frame is wrong
[cs228@rhel4server ~]$
EXPERIMENT No: 6

AIM: Implement Sliding window protocol for Goback N


Source code:

#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;
}
EXPERIMENT No: 7

AIM: Implement Sliding window protocol for Selective


repeat Source code:

#include<stdio.h>

#include<conio.h>

void main()

char sender[50],receiver[50];

int i,winsize;

clrscr();

printf("\n ENTER THE WINDOWS SIZE : ");

scanf("%d",&winsize);

printf("\n SENDER WINDOW IS EXPANDED TO STORE MESSAGE OR WINDOW \n");

printf("\n ENTER THE DATA TO BE SENT: ");

fflush(stdin);

gets(sender);

for(i=0;i<winsize;i++)

receiver[i]=sender[i];

receiver[i]=NULL;

printf("\n MESSAGE SEND BY THE SENDER:\n");

puts(sender);

printf("\n WINDOW SIZE OF RECEIVER IS EXPANDED\n");

printf("\n ACKNOWLEDGEMENT FROM RECEIVER \n");

for(i=0;i<winsize;i++);

printf("\n ACK:%d",i);

printf("\n MESSAGE RECEIVED BY RECEIVER IS : ");


puts(receiver);

printf("\n WINDOW SIZE OF RECEIVER IS SHRINKED \n");

getch();

OUTPUT:

ENTER THE WINDOWS SIZE : 10

SENDER WINDOW IS EXPANDED TO STORE MESSAGE OR WINDOW

ENTER THE DATA TO BE SENT: ForgetCode.com

MESSAGE SEND BY THE SENDER:


ForgetCode.com

WINDOW SIZE OF RECEIVER IS

EXPANDED ACKNOWLEDGEMENT FROM

RECEIVER ACK:5
MESSAGE RECEIVED BY RECEIVER IS : ForgetCode

WINDOW SIZE OF RECEIVER IS SHRINKED


EXPERIMENT No: 8

AIM: Implement Stop and Wait Protocol


Source code:
/* Stop and Wait Protocol ( Flow Control ) */

#include<stdio.h>

#include<bios.h>

#include<conio.h>

#define COM1 0

#define SETTINGS 0x82

#define DTR 0x100

void main()

int ch,status,i=0,true=1;

char msg[100],ack,rec;

clrscr();

bioscom(0,SETTINGS,COM1);

printf("\n 1.Transmit\n 2.Receive"); printf("\

n\n Enter the operation code : ");

scanf("%d",&amp;ch);

switch(ch)

case 1 : printf("\n Enter the Message \n ");

scanf("%s",&amp;msg);

while(msg[i]!='\0')

bioscom(1,msg[i],COM1);

printf("\n%c",msg[i]);

do
{

while(1)

status=bioscom(3,0,COM1);

if(status &amp; DTR)

ack=bioscom(2,0,COM1) &amp; 0x7F;

if(ack=='0')

bioscom(1,msg[i],COM1); printf("\n

%c - retransmitted ",msg[i]);

break;

}while(ack!='1'); i+

+;

break;

case 2 : printf("\n Receiver \t Press Escape to quit\n\n");

do

status=bioscom(3,0,COM1);

if(status &amp; DTR)

rec=bioscom(2,0,COM1);

printf("\n%c -- Enter ACK(1 for +ve, 0 for -ve) :",rec);

ack=getche();
bioscom(1,ack,COM1);

if(kbhit()) if(getch()=='\

x1b') true=0;

}while(true);

break;

default : printf("\n Invalid Selection");

}
EXPERIMENT No: 9

AIM: Congestion control using leaky bucket algorithm


Source code:

#include<stdio.h>

int main(){

int incoming, outgoing, buck_size, n, store = 0;


printf("Enter bucket size, outgoing rate and no of inputs: ");
scanf("%d %d %d", &buck_size, &outgoing, &n);

while (n != 0) {
printf("Enter the incoming packet size : ");
scanf("%d", &incoming);
printf("Incoming packet size %d\n", incoming);

if (incoming <= (buck_size - store)){


store += incoming;
printf("Bucket buffer size %d out of %d\n", store, buck_size);
} else {
printf("Dropped %d no of packets\n", incoming - (buck_size - store));

printf("Bucket buffer size %d out of %d\n", store, buck_size);


store = buck_size;
}
store = store - outgoing;

printf("After outgoing %d packets left out of %d in buffer\n", store, buck_size);

n--;
}

Output:

Commands for execution:-

 Open a terminal.
 Change directory to the file location.
 Run gcc filename.c
 If there are no errors, run ./a.out
Screenshots:-

EXPERIMENT No: 10
AIM: Implement Dijkstra‘s algorithm to compute the Shortest path in a
graph.
Source code:
#include<stdio.h>
int main()

{
int path[5][5],i,j,min,a[5][5],p,st=1,ed=5,stp,edp,t[5],index;
printf("enter the cost matrix \n");
for(i=1;i<=5;i++)
for(j=1;j<=5;j++)
scanf("%d",&a[i][j]);
printf("enter the paths\n");
scanf("%d",&p);
printf("enter possible paths\n");
for(i=1;i<=p;i++) for(j=1;j<=5;j+
+) scanf("%d",&path[i][j]);
for(i=1;i<=p;i++)
{ t[i]=
0;
stp=st;
for(j=1;j<=5;j++)
{
edp=path[i][j+1];
t[i]=t[i]+a[stp][edp];
if(edp==ed)
break;
else
stp=edp;
}
}min=t[st];
index=st;
for(i=1;i<=p;i++)
{
if(min>t[i])
{
min=t[i];
index=i;

}
printf("minimum cost %d",min);
printf("\n minimum cost path ");
for(i=1;i<=5;i++)
{
printf("--> %d",path[index][i]);
if(path[index][i]==ed)
break;
}
return 0;
Output:
[cs228@rhel4server ~]$ vi dijkstra.c
[cs228@rhel4server ~]$ gcc dijkstra.c
[cs228@rhel4server ~]$ ./a.out
enter the cost matrix
01420
10390
43050
27506
13053
12345
enter the paths
4
enter possible paths
12345
12435
13245
12543
minimum cost 1
minimum cost path --> 1--> 2--> 5
[cs228@rhel4server ~]$
output:
[cs228@rhel4server ~]$ vi dvr.c
[cs228@rhel4server ~]$ gcc dvr.c
[cs228@rhel4server ~]$ ./a.out

EXPERIMENT No: 11
AIM: Obtain Routing table at each node using distance vector routing algorithm for a given subnet
Source code:
#include<stdio.h>
int main()
{
int i = 0, a[5], b[5], c[5], d[5], e[5], ab[5];
int ac[5], ad[5], ao[5], ba[5], bc[5], be[5];
int bo[5], ca[5], cb[5], ce[5], co[5], da[5];
int ec[5], eb[5], eo[5], dop[5];
char node[5]={'A', 'B', 'C', 'D', 'E'};
printf(" *** DISTANCE VECTOR ROUTING *** \n\n\n");
printf("\n Enter values for 'a':\n");
for(i = 0; i < 5; i++)
scanf("%d", &a[i]);
printf("\n Enter the values for ‘b’:\n ");
for(i = 0; i < 5; i++)
scanf("%d", &b[i]);
printf("\n Enter the values for ‘c’:\n ");
for(i = 0; i < 5; i++)
scanf("%d", &c[i]);
printf("\n Enter the values for ‘d’:\n ");
for(i = 0; i < 5; i++)
scanf("%d", &d[i]);
printf("\n Enter the values for ‘e’:\n ");
for(i = 0; i < 5; i++)
scanf("%d", &e[i]);
printf("\n\n THE ROUTERS TABLE WITH OPTIMUM VALUES:\n");
printf(" \t \n");
printf("\t A \t B \t C \t D\t E\n");
printf(" \t \n");
printf("%c\t", node[0]);
for(i = 0; i < 5; i++)
{
ab[i] = a[1] + b[i];
ac[i] = a[2] + c[i];
ad[i] = a[3] + d[i];
}
for(i = 0; i < 5; i++)
{
if(a[i] < ab[i] && a[i] < ac[i] &&a[i] < ad[i])
ao[i] = a[i];
else if(ab[i] < ac[i] && ab[i] < ad[i])
ao[i] = ab[i];
else if(ac[i] < ad[i])
ao[i] = ac[i];
else
ao[i] = ad[i];
printf("%d\t", ao[i]);
}
printf("\n %c \t ", node[1]);
for(i = 0; i < 5; i++)
{
ba[i] = b[0] + ao[i];
bc[i] = b[2] + c[i];
be[i] = b[4] + e[i];
}
for(i = 0; i < 5; i++)
{
if(b[i] < ba[i] && b[i] < bc[i] && b[i] < be[i])
bo[i] = b[i];
else if(ba[i] < bc[i] && ba[i] < be[i])
bo[i] = ba[i];
else if(bc[i] < be[i])
bo[i] = bc[i];
else
bo[i] = be[i];
printf("%d\t", bo[i]);
}
printf("\n%c\t", node[2]);
for(i = 0; i < 5; i++)
{
ca[i] = c[0] + ao[i];
cb[i] = c[1] + bo[i];
ce[i] = c[4] + e[i];
}
for(i = 0; i < 5; i++)
{
if(c[i] < ca[i] && c[i] < cb[i] && c[i] < ce[i])
co[i] = c[i];
else if(ca[i] < cb[i] && ca[i] < ce[i])
co[i] = ca[i];
else if(cb[i] < ce[i])
co[i] = cb[i];
else
co[i] = ce[i];
printf("%d\t", co[i]);
}
printf("\n %c \t", node[3]);
for(i = 0; i < 5; i++)
da[i] = d[0] + ao[i];
for(i = 0; i < 5; i++)
{
if(d[i] < da[i])
dop[i] = d[i];
else
dop[i] = da[i];
printf("%d\t", dop[i]);
}
printf("\n%c\t", node[4]);
for(i = 0; i < 5; i++)
{
ec[i] = e[2] + co[i];
eb[i] = e[1] + bo[i];
}
for(i = 0; i < 5; i++)
{
if(e[i] < ec[i] && e[i] < eb[i])
eo[i] = e[i];
else if(ec[i] < eb[i])
eo[i] = ec[i];
else
eo[i] = eb[i];
printf("%d\t", eo[i]);
}
printf("\n\t \n");
printf("\n OPTIMUM COST FROM ROUTER-A TO ROUTER-E:");
printf("%d", ao[4]);
return 0;
}
output:
Enter values for 'a':
12345
Enter the values for ‘b’:
23456
Enter the values for ‘c’:
45678
Enter the values for ‘d’:
13245
Enter the values for ‘e’:
65432
THE ROUTERS TABLE WITH OPTIMUM VALUES:

ABCDE

A12345
B23456
C45678
D13245
E65432

OPTIMUM COST FROM ROUTER-A TO ROUTER-E:5


[cs228@rhel4server ~]$

EXPERIMENT No: 12

AIM: Implement Broadcast tree by taking subnet of hosts


(a)Network Address:
Source code:
#include<stdio.h>
int main()
{
unsigned int compad[4];
unsigned int mask[4];
unsigned int netadr[4];
int i;
printf("Enter the ip address:\n"); scanf("%u%*c%u%*c%u%*c%u
%*c",&compad[3],&compad[2],&compad[1],&compad[0]); printf("Enter the subnet address:\n");
scanf("%u%*c%u%*c%u%*c%u%*c",&mask[3],&mask[2],&mask[1],&mask[0]); for(i=0;i<4;i+
+)
{
netadr[i]= compad[i]&mask[i];
}
printf("\nNetwork address is:\n"); printf("%u.%u.%u.
%u",netadr[3],netadr[2],netadr[1],netadr[0]); printf("\nsubnet address
is:\n"); printf("%u.%u.%u.%u",mask[3],mask[2],mask[1],mask[0]);
printf("\nip address is:\n"); printf("%u.%u.%u.
%u",compad[3],compad[2],compad[1],compad[0]); return 0;
}
Output:
[cs228@rhel4server ~]$ gcc bct.c
[cs228@rhel4server ~]$ ./a.out
Enter the ip address:
192.168.1.7
Enter the subnet address:
255.255.255.0
Network address is:
192.168.1.0
subnet address is:
255.255.255.0
ip address is:
192.168.1.7
[cs228@rhel4server ~]$
(b) Network address with automatic subnet address generation:
Source code:
#include<stdio.h>
int main()
{
unsigned int compad[4];
unsigned int mask[4];
unsigned int netadr[4];
unsigned long int ma=0;
int i,pre;
printf("Enter the ip address:\n"); scanf("%u%*c%u%*c%u%*c%u
%*c",&compad[3],&compad[2],&compad[1],&compad[0]); printf("Enter the prefix:\n");
scanf("%ul",&pre);
for(i=(32-pre);i<32;i++)
ma=ma|(1<<i);
for(i=0;i<4;i++)
{
mask[i]=ma%256;
ma=ma/256;
}
for(i=0;i<4;i++)
{
netadr[i]= compad[i]&mask[i];
}
printf("\nNetwork address is:\n"); printf("%u.%u.%u.
%u",netadr[3],netadr[2],netadr[1],netadr[0]); printf("\nsubnet address
is:\n"); printf("%u.%u.%u.%u",mask[3],mask[2],mask[1],mask[0]);
printf("\nip address is:\n"); printf("%u.%u.%u.
%u",compad[3],compad[2],compad[1],compad[0]);
}
Output:
[cs228@rhel4server ~]$ vi bct-2.c
[cs228@rhel4server ~]$ gcc bct-2.c
[cs228@rhel4server ~]$ ./a.out
Enter the ip address:
192.168.1.7
Enter the prefix:
25
Network address is:
192.168.1.0
subnet address is:
255.255.255.128
ip address is:
192.168.1.7
[cs228@rhel4server ~]$ \

EXPERIMENT No: 13

AIM: Introduction to Wireshark

Introduction

What
● is a network trace?

What
● is Wireshark?
●Basic UI


Some of the most useful parts of the UI.

●Packet Capture


How do we capture packets?

●Trace Analysis

●Individual Packet Analysis

●Filters
Introduction

Network
● Traffic Trace

● A recording of the network packets both receivedby and transmitted from a network interface.

What
● is a pcap file?

● pcap = Packet Capture

● File format originally designed for tcpdump/libpcap.

● Most widely used packet capture format.


What
● is Wireshark?

● A graphical network packet analyser.

● Found at http://www.wireshark.org

● The complete manual is located here.

What
● some are it's uses?

● Troubleshoot network problems.

● Learn network protocol internals.

● Debug protocol/program implementation.

● Examine network-related security issues.


Basic UI
Basic UI

File
● -> Open

● Opens a packet capture file.

View
● -> Time Display Format

● Change the format of the packet timestamps in thepacket list pane.

● Switch between absolute and relative timestamps.

● Change level of precision.

View
● -> Name Resolution

● Allow wireshark to resolve names from addressesat different protocol layers.


Basic UI

Capture-
● >Interfaces

● Available network interfaces forcapture.

● Totalpacketsperinterface.

● Packet rate per interface.


Basic UI

Capture
● -> Options

● Setvariouscaptureparameters.

Promiscous
● mode

● On – recordallpacketsreaching the interface.

● Off– recordonlythosepackets directed to thehost.


Basic UI

Analyze->Follow
● TCPStream

● Applies a filter to follow a single tcp conversationwithin the trace.

● Displays the reassembiled data section of eachpacket in the conversation.

● Useful for debugging or analyzing any TCP basedapplication layer protocol.


HTTP, FTP, SSH, LDAP, SMTP, etc.
Basic UI

Statistics
● -> Protocol Hierarchy

● Presents descriptive statistics


per protocol.

● Useful for determining thetypes, amounts, and


relative proportions of protocols within a
trace.
Basic UI

Statistics
● -> Conversations

● Generates descriptivestatistics about each


conversation for eachprotocol in the
trace.
Basic UI

Statistics->
● Flow Graph

● Generates a sequence graph for the selected


traffic.

● Useful for understandingseq. and ack.


calculations.
Packet Capture

Interface
● selection

● Capture -> Interfaces


Select the interface from which to capture packets.

any – captures from all interfaces

lo – captures from the loopback interface (i.e. from localhost)

Set the desired capture parameters under the optionsmenu.

Start
● Capture

● Click the start button next to the desired interface.

● Captured traffic will be displayed in the packet list pane.


Packet Capture

Stop
● Capture

● Select Capture -> Stop

Saving
● Capture

● Oncethecapturehasbeenstoppedselect File->Save As.

● From the save dialog you can specify file type andwhich packets to save via the packet range menu.
Trace Analysis
Trace Analysis

Packet
● list

● Displays all of the packets in the trace in the order they wererecorded.

● Columns


Time – the timestamp at which the packet crossed theinterface.

Source – the originating host of the packet.

Destination – the host to which the packet was sent.

Protocol – the highest level protocol that Wireshark can detect.

Lenght – the lenght in bytes of the packet on the wire.

Info – an informational message pertaining to the protocol inthe protocol column.
Trace Analysis

Packet
● list

● Default Coloring


Gray – TCP packets


Black with red letters – TCP Packets with errors


Green – HTTP Packets


Light Blue – UDP Packets

Pale Blue – ARP Packets

Lavender – ICMP Packets

Black with green letters – ICMP Packets with errors

● Colorings can be changed under View -> Coloring Rules


Individual Packet Analysis
Individual Packet Analysis

Packet
● Details

● Detailed information about the currently selected packet isdisplayed in the packet details pane.

● All packet layers are displayed in the tree menu.

● Any portion of any layer can be exported via a right click andselecting Export Selected Packet Bytes

Packet
● Bytes

● Displays the raw packet bytes.

● The selected packet layer is highlighted.


Filters

● Filters

Packets
● captures usually contain many packets irrelevant tothe specific analysis task.

To
● remove these packets from display or from the captureWireshark provides the ability to create filters.

Filters
● are evaluted against each individual packet.

Boolean
● expresions dealing with packet properties.

Supportsregularexpressions.

Can
● either be manually constructed, composed via the Expressions menu or composed based on a
selected packet's properties.
Filters

● Expressions Menu

Field
● name – selects thepacket property.

Relation
● – selects theboolean test.

Predefined
● values – commonvalues against
which the selected packet property is tested.

Value – Arbitrary Textual orNumeric value



against
which the selected packet property
is tested.
Filters

● Compound Filters

Filters
● can be composed of multiple tests joined with booleanconnectives.

&& - logical conjuction (i.e. AND)

|| - logical disjunction (i.e OR)

! - logical negation (i.e. NOT)

Supports
● the order of operations.

● Regular Expressions

Fields
● can be evaluated against a regular expression using the“matches” test.

Uses
● Perl regex syntax.
Filters

● Filter Text Box

Green
● – valid filter

Red
● – invalid filter

Yellow
● – may produce unexpected results

● Packet based filters

Filters
● can be constructed on the basis of individual packetsby right clicking on a packet and selecting either:

Prepare as filter – creates a filter.

Apply as filter – creates a filter and applies it to the trace.

Follow TCP Stream – creates a filter from a TCP packet'sstream number and applies it to the trace.
Filters

● Filter examples

http.request
● – Display all HTTP requests.

http.request
● || http.response – Display all HTTP request andresponses.

ip.addr
● == 127.0.0.1 – Display all IP packets whose source ordestination is localhost.

tcp.len
● < 100 – Display all TCP packets whose data length isless than 100 bytes.

http.request.uri
● matches “(gif)$” - Display all HTTP requestsin which the uri ends with “gif”.

dns.query.name
● == “www.google.com” - Display all DNSqueries for “www.google.com
EXPERIMENT No: 14

AIM: Run the Nmap scan

How to start Nmap and run a simple scan ?

Nmap is a free and open-source utility which is used to scan networks and security auditing.
Nmap can discover hosts and services on a computer network by sending packets and
analyzing the responses. The utility is available on almost every os, it is available for windows,
linux and mac.
Download Nmap –
Download Nmap from the official website. In case of kali Linux and parrot os, it is already
available in there so you will not need to download the utility.

How to launch Nmap?

In Windows hosts you can simply install nmap and run it from the desktop icon using
administrator privileges . In linux hosts there are 2 ways of doing it, in case of kali linux and
parrot os you can find the icon and click to start and later give it root privileges by entering
your password .

The other way is you can simply run


nmap --help

You can use it as a manual for using commands, just scroll down and head towards examples.

How to do simple scans and be legal?

As already mentioned, scanning networks and websites using nmap can be illegal, you may need
written permissions to so. So, to do scans that are legal you can use scanme.org, they offer you
to perform scans on their website without any issues, but please read their conditions so that you
do not harm their website.

Now lets see a simple example to do a scan. To do so simply use nslookup command following
the website url or address. If you do not know the IP address of the website and using the
command.
nslookup scanme.nmap.org
will give you its address. Now when you get the address you can use the same for scanning the
network by
nslookup "address"
the address should be written as IP address which you found on the previous scan and without
quotes.

This is how you can do a simple network scan. Now you can also save your scans in a text file
for simplicity by using the command
nslookup 45.33.32.156 >> result.txt

Please note that nmap is a very noisy scanning utility and you need to be anonymous and legal
in some cases to do so. Please ensure that you use it for legal and educational purposes.
EXPERIMENT No: 15

AIM: Operating System Detection using Nmap

How to run Nmap scan?


OS Detection in Nmap in Kali Linux

NMAP stands for Network Mapper which is an open-source tool used for network exploration
and security auditing, in comparison to this, a tool named Nessus is used by industry
professionals. These tools are mainly used by cybersecurity experts and hackers.
Its main purpose is:
 Provide the list of the live host.
 Find the open Ports.
 The real-time information of a network.
 OS and Port scanning.
The hackers and the cybersecurity expert need to know the Operating System of the machine.
It becomes very easy to access a system if we can know the specific open ports or the security
holes of the system. Network Mapper(NMAP) NMAP has a database that helps in
Operating systems (OS) but it is not automatically updated. The database to detect an OS is
located at ‘/usr/share/nmap/nmap-os-db’.
Operating System(OS) detection is a very long and hectic process. So, before we get our
hands dirty we should know about the five separate probes being performed to determine the
OS. This probe may consist of one or more packets. The response to each packet (which is sent
by the probe) by the target system helps to determine the OS type.
The five different probes are:
 Sequence Generation.
 ICMP Echo.
 TCP Explicit Congestion Notification.
 TCP.
 UDP.
1. Sequence Generation: The Sequence Generation Probe consists of six packets that are
sent 100 ms apart and are all TCP SYN packets. The result of all these packets will help
in Operating System(OS) detection.
2. ICMP Echo: Two ICMP request packets are sent to the target system with different
settings in the packet. The result of all these will help verify the OS type by NMAP.
3. TCP Explicit Congestion Notification: Congestion is a slowdown that occurs when a lot
of packets are generated and passed by a single router. The packets which are sent are mainly
used to get back the responses from the target system. This helps to detect the OS because a
specific OS returns a specific value and each OS handles a packet differently.
4. TCP: Six packets are sent during this probe, and some packets are sent to open or closed
ports with specific packet settings by using the corresponding result we can determine the type
of Operating System(OS). The TCP Packets which are sent with varying flags are as follows:
 no flags.
 SYN, FIN, URG, and PSH.
 ACK.
 SYN.
 ACK.
 FIN, PSH, and URG.
5. UDP: UDP probe consists of a single packet that is sent to a closed port. If the port used
on the target system is closed and an ICMP Port Unreachable message is returned it specifies
that there is no Firewall.
OS detection using NMAP
Now we need to run the actual commands to perform OS detection using NMAP, and at first,
we will get the IP address of the host system, and then will perform a scan to get all active
devices on the network.
Step 1: Getting the IP of the System
ifconfig
Step 2: List of active devices in the Network
nmap -sn 192.168.232.128/24

Let’s do an SYN scan with OS detection in one of the active IPs


Let’s select IP: 192.168.232.2
nmap -sS 192.168.232.2 -O
Running: VMware Player.
OS details: VMware Player virtual NAT device.

Let’s now perform an Aggressive scan To guess the OS

 -sV stands for Service version.


 -A stands for Aggressive.
It will only display the chance of Operation System (OS) on the host computer with the help of
Probability and Percentage.
nmap -sV 192.168.232.2 -A
EXPERIMENT No: 16

AIM: Introduction to NS2 Simulator

Network Simulator 2 (NS2) : Features & Basic Architecture Of NS2

(i)

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

ii) /* The Routing Agent */


class AODV: public Agent {

...

/*
* History management

*/

double PerHopTime(aodv_rt_entry *rt);

...
add following line

bool malicious;
With this variable we are trying to define if the node is malicious or not. In aodv.cc after

/*

Constructor

*/

AODV::AODV(nsaddr_t id) : Agent(PT_AODV),btimer(this), htimer(this), ntimer(this),


rtimer(this), lrtimer(this), rqueue() {

index = id;

seqno = 2;

bid = 1;

...
add following line

malicious = false;
The above code is needed to initialize, and all nodes are initially not malicious. Then we will
write a code to catch which node is set as malicious. In aodv.cc after

if(argc == 2) {

Tcl& tcl = Tcl::instance();

if(strncasecmp(argv[1], "id", 2) == 0)

{ tcl.resultf("%d", index);
return TCL_OK;

}
add following line

if(strcmp(argv[1], "hacker") == 0)

{ malicious = true;

return TCL_OK;

}
Now we will do some work in TCL to set a malicious node. Using script in my post , we add
following line to set node 5 as malicious node.

$ns at 0.0 "[$mnode_(5) set ragent_] hacker"


You may add this line after

for {set i 0} {$i &lt; $val(nn)} { incr i } {

$ns initial_node_pos $mnode_($i) 10

...
Alright, we have set malicious node but we did not tell malicious node what to do. As it is
known, rt_resolve(Packet *p) function is used to select next hop node when routing data
packets. So, we tell malicious node just drop any packet when it receives. To do that after

/*

Route Handling Functions

*/

voi

AODV::rt_resolve(Packet *p) {

struct hdr_cmn *ch =

HDR_CMN(p);
struct hdr_ip *ih = HDR_IP(p);

aodv_rt_entry *rt;

...
We add a few lines

// if I am malicious node

if (malicious == true ) {

drop(p, DROP_RTR_ROUTE_LOOP);

// DROP_RTR_ROUTE_LOOP is added for no reason.

(iii) Simulate to Find the Number of Packets Dropped by TCP/UDP

We can simulate a TCP/UDP client using a useful tool called Netcat – so you can establish
connection using your computer’s own terminal.

So,how does the client-server model work within the Internet of things? The client is the
device that initiates communication. The server is Ubidots (or any other server connection),
which will accept connections and manage data transfers over a simple protocol like TCP or
UDP.

To learn more about managing your data with Ubidots, find out how to send data to Ubidots
over TCP or UDP.
What is Netcat?

Netcat is a featured networking utility that reads and writes data across network connections,
using the TCP/IP protocol. Designed as a reliable “back-end” tool, Netcat can be used directly
with other programs and scripts to send files from a client to a server and back. At the same
time, it’s a feature-rich network debugging and exploration tool that can specify network
parameters while also establishing a connection to a remote host via a tunnel.

Although Netcat can do many things, its main purpose and most desirable functions are to:

1. Create an initial socket to establish a connection from the server to the client.
2. Once connected, Netcat will automatically generate a second socket to transmit files from
the server to the client and vice versa. (This is the really cool part).

A diagram of Netcat’s data protocol architecture is shown below:


As you’ll see below, this simple solution is also extraordinarily powerful and flexible. We’ll
use local connections for the sake of simplicity, though of course, they can also be used
between different machines.

Syntax

nc [-options] hostname port[s] [ports]


nc -l -p port [-options] [hostname] [port]

Basic parameters

 -l: set the “listen” mode, waits for the incoming connections.
 -p: local port.
 -u: set the UDP mode.

Test your Netcat understanding as a client-server

Open two computer terminals – the first will act as the server and the second as the client.
TCP client

With Netcat, your PC can be converted into a server. You’ll want to begin as a server that
listens at port 2399:

$ nc -l 2399
We can also use the server to connect to the recently opened port (2399) from the client side:

$ nc localhost 2399
As you can see in the image below, the connection is established:

With the connection established, you can now write to the server from the client:

$ nc localhost 2399 Hello Server


In the terminal where the server is running, your text files will appear seamlessly.

$ nc -l 2399 Hello Server

UDP client

By default,Netcat uses the TCP protocol to communicate – but it can also use UDP with the -
u option.

As we mentioned above, Netcat lets you convert your PC into a server. Here, we’re going to
establish the connection between the server and the client using UDP.
On the server side, run the command below. As you can see, you only need to add -u to the
command to establish the UDP connection:

$ nc -u -l 2399
Once you start the server, establish the connection with the client:

$ nc -u localhost 2399
Now the client and server are using UDP to communicate. You can verify communication
using the netstat command in a new (3rd) computer terminal.

$ netstat | grep 2399


udp 0 0 localhost:2399 localhost:57508 ESTABLISHED
As you can see below, the message is received by the server and the transmission is verified by
the connection:

(iv) Simulate to Find the Number of Packets Dropped due to Congestion.

Simulate the transmission of ping messages over a network topology


consisting of 6 nodes and find the number of packets dropped due to
congestion.
Description:

Ping sends ICMP ECHO_REQUEST to network hosts. Ping uses the ICMP protocol's mandatory
ECHO_REQUEST datagram to elicit an ICMP ECHO_RESPONSE from a host or gateway.
ECHO_REQUEST datagrams ("pings") have an IP and ICMP header, followed by a struct
timeval and then an arbitrary number of ``pad'' bytes used to fill out the packet.

Packages required to be pre-installed:

 (if they dont already exist)


 openjdk6-jre-headless or openjdk7-jre-headless
 nam
 ns2

Instructions to Simulate:

1. Open ns2g2.jar by right clicking on the jar file and choosing open with
java. Ns2g2.jar file is java dependent.
2. On the editing panel, choose Scenario, and select Wired Scenario.
3. The node tab is to be selected next to place the nodes on the grid. This
program requires the user to have 6 nodes in the network. Draw 6 nodes on the
network.
4. The link tab provides the user to link the nodes in the grid. Connect all the nodes.
Select Link type as duplex(bi-directional link), Queue type as
Droptail(indication stating the packets are to be dropped at destination
only), capacity as 1Mbps, propagation delay as 10ms and queue size
as desirable(i.e 5, 10, etc.)
5. After finishing the topology, click on TCL tab. It generates the code and save
it where required as a .tcl file.
6. After saving, open the file in a text editor.(like nano, gedit, vi etc)
7. Now enter the following code under the agent definition header:

8. //creating an agent object

9. set ping0 [new Agent/Ping]

10. //agent object node0

11. $ns attach-agent $n0 $ping0

12. set ping1 [new Agent/Ping]


13. //agent object node1

14. $ns attach-agent $n1 $ping1

15. set ping4 [new Agent/Ping]

16. //agent object node4

17. $ns attach-agent $n4 $ping4

18. set ping5 [new Agent/Ping]

19. //agent object node5

20. $ns attach-agent $n5 $ping5

21. //node2 and node3 acts as an intermediate nodes

22. //$ns connect $source $destination

23. $ns connect $ping0 $ping4

24. $ns connect $ping1 $ping5

25. //function to constantly ping th destination at an interval of 0.01s

26. proc sendPingPacket {} {

27. //global objects

28. global ns ping0 ping1


29. //time interval

30. set time 0.01

31. //sets now with the current time of simulation

32. set now [$ns now]

33. //when the current simulation time($now) + time($time = 0.01) occurs a ping
is sent to the destination

34. $ns at [expr $now + $time] "$ping0 send"

35. $ns at [expr $now + $time] "$ping1 send"

36. //pingPacket is sent

37. $ns at [expr $now + $time] "sendPingPacket"

38. }

39. //In the Tcl code, a procedure 'Agent/Ping recv {from rtt}' has to be defined
which allows the user to react to the ping result.

40. Agent/Ping instproc recv {from rtt} {

41. global seq

42. $self instvar node_


43. }

44. $ns at 0.01 "sendPingPacket"

45. $ns at 10.0 "finish"

46.

47.
48. Save the file.
49.

50. To run it on terminal, tpye the command, ns *filename.tcl*

51. When the code compiles successfully, the Network Animator(nam) will automatically
open for the simulation.

52. In nam, click on the play button and simulation will be run.

53. Once the simulation ends, in the terminal, type cat out.tr | grep ^d | wc -l to know the
number of packets dropped.

54. Multiple scenarios can be generated by changing the values of bandwidth and queue
size of the links in the ns2.
Screenshots:-
V)

1 set ns [new Simulator]


2
3 #Open the trace file
4 set nd [open out.tr w]
5 $ns trace-all $nd
6
7 #Set the size of the TCP stream
8 set nflow 5
9
10 #Set the router (in ns2, the router is the node)
11 set r1 [$ns node]
12 set r2 [$ns node]
13 $ns duplex-link $r1 $r2 1Mb 10ms DropTail
14
15 #Set the maximum value of the queue buffer between r1 and r2 to 10 packets, and the default
size of each packet is 40 bytes, ~/ns/tcl/lib/ns-default.tcl
16 $ns queue-limit $r1 $r2 10
17
18 #Set the source node and destination node of TCP, three each, and connect to two routers resp
ectively
19 for {set i 1} {$i <= $nflow} {incr i} {
20 set s($i) [$ns node]
21 set d($i) [$ns node]
22
23 $ns duplex-link $s($i) $r1 10Mb 1ms DropTail
24 $ns duplex-link $d($i) $r2 10Mb 1ms DropTail
25 }
26
27 #Establish TCP one-way proxy, tcp(i) is the sender, sink(i) is the receiver, and connect to
the corresponding nodes respectively, then establish a TCP connection, and establish an FTP
applica tion on TCP
28 for {set i 1} {$i <= $nflow} {incr i} {
29 set tcp($i) [new Agent/TCP]
30 set sink($i) [new Agent/TCPSink]
31 $ns attach-agent $s($i) $tcp($i)
32 $ns attach-agent $d($i) $sink($i)
33 $ns connect $tcp($i)
$sink($i) 34
35 set ftp($i) [new Application/FTP]
36 $ftp($i) attach-agent $tcp($i)
37 $tcp($i) set type_ FTP
38 }
39
40 set rng [new RNG] ;#Set the random number generator
41 $rng seed 1
42
43 set RVstart [new RandomVariable/Uniform]
44 $RVstart set min_ 0
45 $RVstart set max_ 1
46 $RVstart use-rng
$rng 47
48
49 for {set i 1} {$i <= $nflow} {incr i} {
50 set startT($i) [expr [$RVstart value]]
51 puts "startT($i) $startT($i) sec"
52 set endT($i) [expr ($startT($i) + 5)]
53 puts "endT($i) $endT($i) sec"
54
55 $ns at $startT($i) "$ftp($i) start"
56 $ns at $endT($i) "$ftp($i) stop"
57 }
58
59 proc finish {} {
60 global ns
nd 61
62 close $nd
63 $ns flush-trace
64 exit 0
65 }
66
67 $ns at 7.0 "finish"
68 $ns run

You might also like