12 CNS Lab Manual 2023-24

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

SINHGAD TECHNICAL EDUCATION SOCIETY’S

SINHGAD INSTITUTE OF TECHNOLOGY


Kusgaon (Bk), Lonavala 410401

DEPARTMENT OF COMPUTER ENGINEERING

LAB MANUAL
ACADEMIC YEAR (2022-23) SEMESTER-V

T.E. COMPUTER (SEM – V)


310247: Computer Networks and Security Laboratory

TEACHING SCHEME EXAMINATION


PRACTICAL: 2 HRS/WEEK TERM WORK: 25 MARKS
ORAL EXAM: 25 MARKS
Vision and Mission of Institute

VISION

We are committed to produce not only good engineers but good


human beings, also.

MISSION

• We believe in and work for the holistic development of students.


• We strive to achieve this by imbibing a unique value system, transparent work
culture, excellent academic and physical environment conducive to learning,
creativity and technology transfer.

Vision and Mission of Department

VISION

• The department of Computer Engineering in partnership with user industry


will harness knowledge and Potential for application based product development in
future, through world class education to empower the society around.

MISSION
• The department of Computer Engineering will be the widely recognized
centers of excellence for promoting value added engineering education. We
will contribute by evolving innovative technology solution to solve a wide
range of complex scientific, technological and social problems.

Short Term Goals


• To establish post graduate program in different domain.
• To encourage faculty by creating opportunity of higher education.
• To initiate relevant value addition programs and certifications for improving
employability.
• Build strong alliances that bring know-how of business community to
complete training of students through projects.
Long Term Goals
• To establish a center of innovation in Agriculture, Tele health and ICT sector
in collaboration with industry.
• To create center of excellence in network, security and computer vision.
• To establish a world class R&D institute for patent based research creating
opportunity for faculty to be resource.

Program Educational Objectives (PEO’s)


1. To prepare globally competent graduates having strong fundamentals and
domain knowledge to provide effective solutions for engineering problems.
2. To prepare the graduates to work as a committed professional with strong
professional ethics and values, sense of responsibilities, understanding of
legal, safety, health, societal, cultural and environmental issues.
3. To prepare committed and motivated graduates with research attitude,
lifelong learning, investigative approach, and multidisciplinary thinking.
4. To prepare the graduates with strong managerial and communication skills to
work effectively as individual as well as in teams.
Program Outcomes: POs

Students are expected to know and be able –


PO1- Engineering Knowledge: - To apply knowledge of mathematics, science,
engineering fundamentals, problem solving skills, algorithmic analysis and
mathematical modelling to the solution of complex engineering problems.
PO2- Problem Analysis: - Identify, formulate, review research literature and analyze
complex engineering problems reaching substantiated conclusion using first
principals of mathematics, natural sciences and engineering sciences.
PO3- Design / Development of solutions: - Design solutions for complex engineering
problems and design system components or processes that meet the specified needs
with appropriate considerations for the public health and safety, and the cultural,
social 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 modeling to complex engineering activities with an understanding of the
limitations.
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 societal 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 engineering practice.
PO9- Individual and Team work :-Function effectively as an individual and as a
member or leader in diverse teams, and in multidisciplinary settings.
PO10- Communication Skill:- 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 dear instructions.
PO11- Project management Finance: - Demonstrate knowledge and understanding of
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 multidisciplinary
environment. PO12- Life-long Learning: - Recognize the need for, and have the
preparations and ability to engage in independent and lifelong learning in the broadest
context of technological change.

Program Specific Outcomes: PSOs

A graduate of the Computer Engineering Program will demonstrate-


PSO1- Professional Skills-The ability to understand, analyze and develop computer
programs in the areas related to algorithms, system software, multimedia, web design,
big data analytics, and networking for efficient design of computer-based systems of
varying.
PSO2- Problem-Solving Skills- The ability to apply standard practices and strategies
in software project development using open-ended programming environments to
deliver a quality product for business success.
PSO3- Successful Career and Entrepreneurship- The ability to employ modern
computer languages, environments, and platforms in creating innovative career paths
to be an entrepreneur, and a zest for higher studies.
SINHGAD INSTITUTE OF TECHNOLOGY

DEPARTMENT OF COMPUTER ENGINEERING

CERTIFICATE

This is to certify that, ______________________ of Class __

Div. __ Roll No.__ Exam Seat No.___________ has completed all the

practical work in the subject Computer Networks and Security

Laboratory, satisfactorily, as prescribed by Savitribai Phule Pune

University, Pune (SPPU) in the Academic Year 2022-23.

Prof. Dr. S.D.Babar

Subject In-charge Head of Department


INDEX
Ass.
Assignment Title
No.
Group A Marks Sign
Setup a wired LAN using Layer 2 Switch and then IP switch of minimum
four computers. It includes preparation of cable, testing of cable using
line tester, configuration machine using IP addresses, testing using PING
1 utility and demonstrate the PING packets captured traces using
Wireshark Packet Analyzer Tool.

Demonstrate the different types of topologies and types of transmission


2 media by using a packet tracer tool

3 To implement error detection and correction techniques

To demonstrate Go back N and Selective Repeat Modes of Sliding


4 Window Protocol in peer to peer mode.

Group B

To Demonstrate subnetting concepts and also find subnet mask


5 of network.

Write a program to implement link state /Distance vector routing


6 protocol to find suitable path for transmission.

To Configure RIP/OSPF/BGP using packet tracer


7

To implement of socket programming for TCP using C.


8

9 To implement UDP socket to enable file transfer.

Group C

10 To study DNS lookup.

Installing and configure DHCP server and write a program to install the
11 software on remote machine

To capture packets using Wireshark, write the exact packet capture filter
12 expressions to accomplish the following and save the output in file

Study and Analyze the performance of HTTP, HTTPS and FTP


protocol using Packet tracer tool.
13

To Study IPsec (ESP and AH) protocol by capturing packets using


Wireshark tool.
14
Computer Network & Security Lab [CNSL] Computer Engineering Department

Experiment No-01

AIM: To establish a wired LAN for four computers.

OBJECTIVES:
• To study wired LAN using switch.
• To understand setup of LAN using switch.
• To implement use of switch.

PROBLEM STATMENT:
Setup a wired LAN using Layer 2 Switch and then IP switch of minimum four computers. It
includes preparation of cable, testing of cable using line tester, configuration machine using IP
addresses, testing using PING utility and demonstrate the PING packets captured traces using
Wireshark Packet Analyzer Tool.

OUTCOMES:
CO1: Demonstrate LAN and WAN protocol behavior using Modern Tools.

SOFTWARE & HARDWARE REQUIREMENTS:

• Software: Open source O.S.and wireshark

• Hardware: Computer, LAN Cards, RJ-45 Connectors, Switch, CAT-


5 Cable, Cable tester, Crimping tool, etc.

THEORY:

Computer Networks, the widespread sharing of information among groups of computers and
their users, a central part of the information age. The popular adoption of the personal computer
(PC) and the local area network (LAN) during the 1980s has led to the capacity to access
information on a distant database; download an application from overseas; send a message to a
friend in a different country; and share files with a colleague—all from a personal computer.

SIT, Lonavala. Page 1


Computer Network & Security Lab [CNSL] Computer Engineering Department

The networks that allow all this to be done so easily are sophisticated and complex entities. They rely
for their effectiveness on many cooperating components. The design and deployment of the
worldwide computer network can be viewed as one of the great technological wonders of recent
decades.

Networks are connections between groups of computers and associated devices that allow users to
transfer information electronically. The local area network shown on the left is representative of
the setup used in many offices and companies. Individual computers, called work stations (WS),
communicate to each other via cable or telephone line linking to servers. Servers are computers
exactly like the WS, except that they have an administrative function and are devoted entirely to
monitoring and controlling WS access to part or all of the network and to any shared resources
(such as printers). The red line represents the larger network connection between servers, called
the backbone; the blue line shows local connections. A modem (modulator/demodulator) allows
computers to transfer information across standard telephone lines. Modems convert digital signals
into analogue signals and back again, making it possible for computers to communicate, or
network, across thousands of miles.

SIT, Lonavala. Page 2


Computer Network & Security Lab [CNSL] Computer Engineering Department

Study of Network Devices:- NIC (Network Interface Card):-

Each computer includes the File server or a Network will have a card plugged in the PCI
Expunction slot or will have on-board NIC (Network Interface Card), which will provide
connectivity among the workstation in the network through cables.

Types of Card:-

1. Arc net card (2.5 mbits/sec)


2. Ethernet card (10/100 mbps)
3. Token Ring card (4-16 mbits/sec)

Hub/Switch:-
These devices are used for Re-directing traffic, i.e. in a
Star Topology the central device is used to
ECHO/Re-Direct the packets coming from one
workstation/node to the Destination workstation/node.

This is done by using the devices like Hub/Switch,


during the present situation. Hubs are absolute due to their disadvantages of Echoing a packet from
one node to all, which leads to increasing N/W traffic and packet Collision.

SIT, Lonavala. Page 3


Computer Network & Security Lab [CNSL] Computer Engineering Department

Type of Hub:-

1. Passive Hub:-
It is a device which do not require any type of power supply and does not boost incoming
signal, it just echo the incoming signal to all nodes.

2. Active Hub :-
It is a device which requires power supply and boosts the incoming signal and echoes the
signal to all nodes. Hub where absolute due to use of an intelligent device called Switch
which reads the destination adders and sends the incoming packet to it.

Paring Rules and Color Code:-

The CAT 5 Cable consist of 8 wires which comes pares of White/Blue, Blue, White/Orange,
Orange, White/Green, Green, White/Brown, Brown and they are coded for Straight and Cross
combinations respectively.

Paring Rules and Color Code:-

The CAT 5 Cable consist of 8 wires which comes pares of White/Blue, Blue, White/Orange,
Orange, White/Green, Green, White/Brown, Brown and they are coded for Straight and Cross
combinations respectively.

Pair # Wire Pin #

1-White/Blue White/Blue 5

Blue 4

2-Wht./Orange White/Orange 1

SIT, Lonavala. Page 4


Computer Network & Security Lab [CNSL] Computer Engineering Department

Orange 2

Straight: 3-White/Green White/Green 3

Green 6

4-White/Brown White/Brown 7

Brown 8

Pair # Wire Pin #

1-White/Blue White/Blue 5
Cross:
Blue 4

2-White/Green White/Green 1

Green 2

3-White/Orange White/Orange 3

Orange 6

4-White/Brown White/Brown 7

Brown 8

SIT, Lonavala. Page 5


Computer Network & Security Lab [CNSL] Computer Engineering Department

Connections among devices:-

Node to Node - Straight – Cross,

Switch to Node - Straight – Straight,

Switch to Switch - Straight – Cross.

How to Crimp a Cat 5 cable with RJ 45 Connector:-

1. Skin off the cable jacket approximately 1" or slightly more.

2. Un-twist each pair, and straighten each wire between the fingers.

3. Place the wires in the order of one of the two diagrams shown above .Bring all of the wires
together, until they touch.

4. At this point, recheck the wiring sequence with the diagram.

5. Optional: Make a mark on the wires at 1/2" from the end of the cable jacket.

6. Hold the grouped (and sorted) wires together tightly, between the thumb, and the
forefinger.

7. Cut all of the wires at a perfect 90 degree angle from the cable at 1/2" from the end of the
cable jacket. This is a very critical step. If the wires are not cut straight, they may not all
make contact. We suggest using a pair of scissors for this purpose.

8. Conductors should be at a straight 90 degree angle, and be 1/2" long, prior to insertion into
the connector.

9. Insert the wires into the connector (pins facing up).

10. Push moderately hard to assure that all of the wires have reached the end of the connector.
Be sure that the cable jacket goes into the back of the connector by about 3/16".

SIT, Lonavala. Page 6


Computer Network & Security Lab [CNSL] Computer Engineering Department

11. Place the connector into a crimp tool, and squeeze hard so that the handle reaches its full
swing.

12. Repeat the process on the other end. For a straight through cable, use the same wiring.

13. Use a cable tester to test for proper continuity.

Cable Testing Tool:-

It is a tool used for testing weather there is no cut in between two terminals and to identify the type
of pair crimp with.

Just as routers direct traffic on the Internet, sending information to its proper destination,
and routers on an intranet perform the same function. Routers-equipment that is a combination of
hardware and software-can send the data to a computer on the same sub network inside the intranet,
to another network on the intranet, or outside to the Internet. They do this by examining header
information in IP packets, and then sending the data on its way. Typically, a router will send the
packet to the next router closest to the final destination, which in turn sends it to an even closer
router, and so on, until the data reaches its intended recipient.

A router has input ports for receiving IP packets, and output ports for sending those packets
toward their destination. When a packet comes to the input port, the router examines the packet
header, and checks the destination in it against a routing table-a database that tells the router how
to send packets to various destinations. Based on the information in the routing table, the packet
is sent to a particular output port, which sends the packet to the next closest router to the packet's
destination.

If packets come to the input port more quickly than the router can process them, they are sent to a
holding area called an input queue. The router then processes packets from the queue in the order
they were received. If the number of packets received exceeds the capacity of the queue (called
the length of the queue), packets may be lost.

SIT, Lonavala. Page 7


Computer Network & Security Lab [CNSL] Computer Engineering Department

In a simple intranet that is a single, completely self-contained network, and in which there
are no connections to any other network or the intranet, only minimal routing need be done, and
so the routing table in the router is exceedingly simple with very few entries, and is constructed
automatically by a program called ifconfig

CONCLUSION:-Hence, we have demonstrate a wired LAN for four computers.

SIT, Lonavala. Page 8


Computer Network & Security Lab [CNSL] Computer Engineering Department

Experiment No-02

AIM: Demonstrate the different types of topologies and types of transmission media by using a
packet tracer tool

OBJECTIVES:
• To study wired LAN using switch.
• To understand setup of LAN using switch.
• To implement use of switch.

PROBLEM STATMENT:

Demonstrate the different types of topologies and types of transmission media by using a packet
tracer tool
OUTCOMES:
CO1: Demonstrate LAN and WAN protocol behavior using Modern Tools.

SOFTWARE & HARDWARE REQUIREMENTS:

• Software: Open source O.S.and wireshark, Cisco packet tracer tool

• Hardware: Computer, LAN Cards, RJ-45 Connectors, Switch, CAT-


5 Cable, Cable tester, Crimping tool, etc.

THEORY:

Demonstrate the all types of topologies using packet tracer tool

SIT, Lonavala. Page 9


Computer Network & Security Lab [CNSL] Computer Engineering Department

1. Bus Topologies:-
In a bus network configuration, each node is
connected to one main communications line. With this
arrangement, even if one of the nodes goes down, the rest
of the network can continue to function normally.

2. Star Topologies:-

A star network consists of several nodes connected


to a central hub/switch in a star-shaped
configuration. Messages from individual nodes pass
directly to the hub/switch, which determines any
further routing.

3. Ring Topology:-

Token Ring Network, in computer science, a LAN


formed in a ring (closed loop) topology that uses token
passing as a means of regulating traffic. On a token
ring network, a token governing the right to transmit is
passed from one station to the next in a physical circle.
If a station has information to transmit, it “seizes” the
token, marks it as being in use, and inserts the
information. The “busy” token, plus message, is then
passed around the circle, copied when it arrives at its

SIT, Lonavala. Page 10


Computer Network & Security Lab [CNSL] Computer Engineering Department

destination, and eventually returned to the sender. The sender removes the attached message and
then passes the freed token to the next station in line. Token ring networks are defined in the IEEE
802.5 standards.

4. Mesh Topology:-

The type of network topology in which each of the


nodes of the network is connected to each of the other
nodes in the network with a point-to-point link – this
makes it possible for data to be simultaneously transmitted
from any single node to all of the other nodes.

5. Hybrid/Tree Topology:-
A tree topology combines characteristics of linear bus
and star topologies. It consists of groups of starconfigured
workstations connected to a linear bus backbone cable.

These topologies can also be mixed. For example, a


bus-star network consists of a high-bandwidth bus, called
the backbone, which connects a collection of
slowerbandwidth star segments.

How Routers Work:

SIT, Lonavala. Page 11


Computer Network & Security Lab [CNSL] Computer Engineering Department

Routers are the traffic cops of intranets. They make sure that all data gets sent to where it's
supposed to go and that it gets sent via the most efficient route. Routers are also useful tools to
make the most efficient use of the intranet. Routers are used to segment traffic and provide
redundancy of routes. Routers use encapsulation to permit different protocols to be sent across
otherwise incompatible networks.

CONCLUSION:-Hence, we have demonstrate all networking topology.

SIT, Lonavala. Page 12


Computer Network & Security Lab [CNSL] Computer Engineering Department

Experiment No -03

AIM: To implement error detection and correction techniques.

OBJECTIVES:
• To study error detection and correction.
• To understand CRC and Hamming code techniques.
• To implement CRC and Hamming code techniques.

PROBLEM STATMENT:

Write a program for error detection and correction for 7/8 bits ASCII codes using Hamming
Codes or CRC. Demonstrate the packets captured traces using Wireshark Packet Analyzer Tool
for peer to peer mode

OUTCOMES:

CO2: Analyze data flow between peer to peer in an IP network using Application, Transport and
Network Layer Protocols

SOFTWARE & HARDWARE REQUIREMENTS:

• Software: Jdk and wireshark


• Hardware: Open source Linux operating system.

THEORY:

Cyclic Redundancy Check: CRC


• Given a k-bit frame or message, the transmitter generates an n-bit sequence, known as a
frame check sequence (FCS), so that the resulting frame, consisting of (k+n) bits, is exactly
divisible by some predetermined number.
• The receiver then divides the incoming frame by the same number and, if there is no
remainder, assumes that there was no error.

SIT, Lonavala. Page 13


Computer Network & Security Lab [CNSL] Computer Engineering Department

Example:

Hamming code:

• Hamming codes are a family of linear error-correcting codes that generalize the
Hamming(7,4)-code

• Invented by Richard Hamming in 1950

Hamming codes can detect up to two-bit errors or correct one-bit errors without detection of
uncorrected errors

General algorithm:

• The following general algorithm generates a single-error correcting (SEC) code for any
number of bits.

• Number the bits starting from 1: bit 1, 2, 3, 4, 5, etc.

• Write the bit numbers in binary: 1, 10, 11, 100, 101, etc.

• All bit positions that are powers of two (have only one 1 bit in the binary form of their
position) are parity bits: 1, 2, 4, 8, etc. (1, 10, 100, 1000)

• All other bit positions, with two or more 1 bits in the binary form of their position, are data
bits.

• Each data bit is included in a unique set of 2 or more parity bits, as determined by the binary
form of its bit position.

SIT, Lonavala. Page 14


Computer Network & Security Lab [CNSL] Computer Engineering Department

• Each data bit is included in a unique set of 2 or more parity bits, as determined by the binary
form of its bit position.

• Parity bit 1 covers all bit positions which have the least significant bit set: bit 1 (the parity
bit itself), 3, 5, 7, 9, etc.

• Parity bit 2 covers all bit positions which have the second least significant bit set: bit 2 (the
parity bit itself), 3, 6, 7, 10, 11, etc.

• Parity bit 4 covers all bit positions which have the third least significant bit set: bits 4–7,
12–15, 20–23, etc.

• Parity bit 8 covers all bit positions which have the fourth least significant bit set: bits 8–15,
24–31, 40–47, etc.

• In general each parity bit covers all bits where the bitwise AND of the parity position and
the bit position is non-zero.

Example

Error detection & correction:

SIT, Lonavala. Page 15


Computer Network & Security Lab [CNSL] Computer Engineering Department

Example of Hamming Code Generation

Suppose a binary data 1001101 is to be transmitted. To implement hamming code for this,
following steps are used:

1. Calculating the number of redundancy bits required. Since number of data bits is

SIT, Lonavala. Page 16


Computer Network & Security Lab [CNSL] Computer Engineering Department

7, the value of r is calculated as

2r > m + r + 1

24 > 7 + 4 + 1

Therefore no. of redundancy bits = 4

3. Determining the positions of various data bits and redundancy bits. The various r
bits are placed at the position that corresponds to the power of 2 i.e. 1, 2, 4, 8

SIT, Lonavala. Page 17


Computer Network & Security Lab [CNSL] Computer Engineering Department

4. Thus data 1 0 0 1 1 1 0 0 1 0 1 with be transmitted.


Error Detection & Correction

Considering a case of above discussed example, if bit number 7 has been changed from 1 to
0.The data will be erroneous.

SIT, Lonavala. Page 18


Computer Network & Security Lab [CNSL] Computer Engineering Department

Write a program for error detection and correction for 7/8 bits ASCII codes using
Hamming Codes
#include<stdio.h>
//#include<conio.h>

void main() { int data[10];


int dataatrec[10],c,c1,c2,c3,i;
// clrscr();
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]);


//getch();
}
}
}

/* output
proglab@proglab:~$ ./a.out Enter 4 bits of data one by
one
1
SIT, Lonavala. Page 19
Computer Network & Security Lab [CNSL] Computer Engineering Department

0
1
1

Encoded data is
1010101

Enter received data bits one by one


0
1
1
0
1
1
0

Error on position 2
Data sent : 1010101
Data received : 0110110
Correct message is
0110100

CONCLUSION: - Hence we have implemented CRC and Hamming code.

SIT, Lonavala. Page 20


Computer Network & Security Lab [CNSL] Computer Engineering Department

Experiment No -04

AIM: To demonstrate Go back N and Selective Repeat Modes of Sliding Window Protocol in peer
to peer mode.

OBJECTIVES:

• To study sliding window protocol.


• To implement Go back N and Selective Repeat Protocol.
• To differentiate between Go back N and Selective Repeat Protocol.

PROBLEM STATMENT:
Write a program to simulate Go back N and Selective Repeat Modes of Sliding Window Protocol
in peer to peer mode and demonstrate the packets captured traces using Wireshark Packet Analyzer
Tool for peer to peer mode.

OUTCOMES:
CO2: Analyze data flow between peer to peer in an IP network using Application, Transport and
Network Layer Protocols

SOFTWARE & HARDWARE REQUIREMENTS:

• Software: jdk compiler and wireshark.


• Hardware: PC-2.

THEORY:

The basic idea of sliding window protocol is that both sender and receiver keep a ‘window’
of acknowledgment. The sender keeps the value of expected acknowledgment; while the
receiver keeps the value of expected receiving frame. When it receives an acknowledgment
from the receiver, the sender advances the window. When it receives the expected frame, the
receiver advances the window.

In transmit flow control, sliding window is a variable-duration window that allows a sender to
transmit a specified number of data units before an acknowledgement is received or before a
specified event occurs.

Flow Control is a set of procedures that tells the sender how much data it can transmit before it
must wait for an acknowledgment from the receiver. The flow of data should not be allowed to
SIT, Lonavala. Page 21
Computer Network & Security Lab [CNSL] Computer Engineering Department

overwhelm the receiver. Receiver should also be able to inform the transmitter before its limits
(this limit may be amount of memory used to store the incoming data or the processing power at
the receiver end) are reached and the sender must send fewer frames. Hence, Flow control refers
to the set of procedures used to restrict the amount of data the transmitter can send before waiting
for acknowledgment.
There are two methods developed for flow control namely Stop-and-wait and Sliding-window
Sliding window algorithms, used by TCP, permit multiple data packets to be in simultaneous
transit, making more efficient use of network bandwidth.

Sliding Window Protocol:

With the use of multiple frames for a single message, the stop-and-wait protocol does not perform
well. Only one frame at a time can be in transit. Efficiency can be greatly improved by allowing
multiple frames to be in transit at the same time. Efficiency can also be improved by making use
of the full-duplex line. To keep track of the frames, sender station sends sequentially numbered
frames. Since the sequence number to be used occupies a field in the frame, it should be of limited
size. If the header of the frame allows k bits, the sequence numbers range from 0 to
2k – 1. Sender maintains a list of sequence numbers that it is allowed to send (sender window).

The size of the sender’s window is at most 2k – 1. The sender is provided with a buffer equal to
the window size. Receiver also maintains a window of size 2k – 1. The receiver acknowledges a
frame by sending an ACK frame that includes the sequence number of the next frame expected.
This also explicitly announces that it is prepared to receive the next N frames, beginning with the
number specified. This scheme can be used to acknowledge multiple frames. It could receive
frames 2, 3, 4 but withhold ACK until frame 4 has arrived. By returning an ACK with sequence
number 5, it acknowledges frames 2, 3, 4 in one go. The receiver needs a buffer of size 1.

Sliding window algorithm is a method of flow control for network data transfers. TCP, the
Internet's stream transfer protocol, uses a sliding window algorithm.

A sliding window algorithm places a buffer between the application program and the network data
flow. For TCP, the buffer is typically in the operating system kernel, but this is more of an
implementation detail than a hard-and-fast requirement.

SIT, Lonavala. Page 22


Computer Network & Security Lab [CNSL] Computer Engineering Department

Data received from the network is stored in the buffer, from where the application can read at its
own pace. As the application reads data, buffer space is freed up to accept more input from the
network. The window is the amount of data that can be "read ahead" - the size of the buffer, less
the amount of valid data stored in it. Window announcements are used to inform the remote host
of the current window size.
An example of a sliding window in packet transmission is one in which, after the sender fails
to receive an acknowledgement for the first transmitted packet, the sender "slides" the window,
i.e. resets the window, and sends a second packet. This process is repeated for the specified
number of times before the sender interrupts transmission. Sliding window is sometimes
(loosely) called acknowledgement delay period.

Go-Back-N Protocol and “Selective Repeat Protocol” are the sliding window protocols. The
sliding window protocol is primarily an error control protocol, i.e. it is a method of error
detection and error correction. The basic difference between go-back-n protocol and selective
repeat protocol is that the “go-back-n protocol” retransmits all the frames that lie after the
frame which is damaged or lost. The “selective repeat protocol” retransmits only that frame
which is damaged or lost.
Go back N ARQ

SIT, Lonavala. Page 23


Computer Network & Security Lab [CNSL] Computer Engineering Department

In the Go-Back-N Protocol, the sequence numbers are modulo 1!", Where
m is the size of the sequence number field in bits.

Selective Repeat ARQ

Go-Back-N ARQ simplifies the process at the receiver site. The receiver keeps track of only one
variable, and there is no need to buffer out-of-order frames; they are simply discarded. However,
this protocol is very inefficient for a noisy link. In a noisy link a frame has a higher probability of
damage, which means the resending of multiple frames. This resending uses up the bandwidth and
slows down the transmission. For noisy links, there is another mechanism that does not resend N
frames when just one frame is damaged; only the damaged frame is resent. This mechanism is
called Selective Repeat ARQ.

Key Differences between Go-Back-N and Selective Repeat

SIT, Lonavala. Page 24


Computer Network & Security Lab [CNSL] Computer Engineering Department

1. Go-Back-N protocol is design to retransmit all the frames that are arrived after the
damaged or a lost frame. On the other hand, Selective Repeat protocol retransmits only
that frame that is damaged or lost.
2. If the error rate is high i.e. more frames are being damaged and then retransmitting all the
frames that arrived after a damaged frame waste the lots of bandwidth. On the other hand,
selective repeat protocol re-transmits only damaged frame hence, minimum bandwidth is
wasted.
3. All the frames after the damaged frame are discarded and the retransmitted frames arrive
in a sequence from a damaged frame onwards, so, there is less headache of sorting the
frames hence it is less complex. On the other hand only damaged or suspected frame is
retransmitted so, extra logic has to be applied for sorting hence, it is more complicated.
4. Go-Back-N has a window size of N-1 and selective repeat have a window size
<=(N+1)/2.
5. Neither sender nor receiver need the sorting algorithm in Go-Back-N whereas, receiver
must be able to sort the as it has to maintain the sequence.
6. In Go-Back-N receiver discards all the frames after the damaged frame hence, it don’t
need to store any frames. Selective repeat protocol does not discard the frames arrived
after the damaged frame instead it stores those frames till the damaged frame arrives
successfully and is sorted in a proper sequence.
7. In selective repeat NAK frame refers to the damaged frame number and in Go-Back-N,
NAK frame refers to the next frame expected.
8. Generally the Go-Back-N is more is use due to its less complex nature instead of
Selective Repeat protocol.

Write a program to simulate Go back N and Selective Repeat Modes of Sliding Window Protocol in Peer-to-Peer mode
#include <stdio.h>

#include <conio.h>
#include <math.h>
int n, r;
struct frame
{
char ack;
int data;

} frm[10]; int sender(void); void


recvack(void); void resend_sr(void);
void resend_gb(void);
void selective(void);

SIT, Lonavala. Page 25


Computer Network & Security Lab [CNSL] Computer Engineering Department

void goback()
{
sender(); recvack();
sender();
printf("\n all frames sent succesfully \n");
}
void selective()
{
sender(); recvack();
resend_sr();
printf("\n all frames sent succesfully \n");
}
int sender()
{
int i,data;
printf("\nEnter the no.of frames to be sent:"); scanf("%d", &n);
for (i = 1; i <= n; i++)
{
printf("\nEnter the data for frames [%d]", i);
scanf("%d", &frm[i], data);
frm[i].ack = 'y';
}
return 0;
}
void recvack()
{
int i; rand();
r = rand() % n;

frm[r].ack = 'n';
for (i =1;i <= n; i++)
{
if (frm[i].ack == 'n')
printf("\nThe frame number %d is not recieved\n", r);
}
}
void resend_sr()
{
printf("\nresending frame %d", r); sleep(2);
frm[r].ack = 'y';
printf("\nThe received frame is %d", frm[r].data);
}
/*int resend_gb()
{
int i,data;
printf("\nEnter the no.of frames to be sent:"); scanf("%d", &n);
for (i = 1; i <= n; i++)
{
printf("\nEnter the data for frames [%d]", i); scanf("%d", &frm[i], data);
frm[i].ack = 'y';
}

SIT, Lonavala. Page 26


Computer Network & Security Lab [CNSL] Computer Engineering Department

return 0;
}
/*void resend_gb()
{
int i;
printf("\nAgain send frame %d", r); for (i = r;i <= n; i++)
{
sleep(2);
frm[i].ack = 'y';
printf("\n received data of frame %d is %d", i, frm[r].data);
}
}*/ int main()
{
int c;
do
{
printf("\n\n1.Selective repeat ARQ\n2.GOback ARQ\n3.exit");

printf("\nEnter your choice:");


scanf("%d", &c); switch (c)
{
case 1:
selective();
break; case
2: goback();
break; case 3:
exit(0);
break;
}
} while (c >= 4);
}

CONCLUSION: - Hence we have implemented of sliding window protocol (Go back N and
Selective Repeat).

SIT, Lonavala. Page 27


Computer Network & Security Lab [CNSL] Computer Engineering Department

Experiment No -05

AIM: To understand subnetting concepts and also find subnet mask of network.

OBJECTIVES:

• To study subnetting concept.


• To find subnet mask of network.
• To demonstrate subnetting.

PROBLEM STATMENT:

Write a program to demonstrate subnetting and find subnet mask.

OUTCOMES:

CO2: Analyze data flow between peer to peer in an IP network using Application, Transport and
Network Layer Protocols

SOFTWARE & HARDWARE REQUIREMENTS:

• Software: jdk & python

• Hardware: Open source Linux operating system.

THEORY:

What is IP address?

An Internet Protocol address (IP address) is a numerical label assigned to each device (e.g.,
computer, printer) participating in a computer network that uses the Internet Protocol for
communication. An IP address serves two principal functions: host or network interface
identification and location addressing. IP address is a 32 bit number. It is universally unique

SIT, Lonavala. Page 28


Computer Network & Security Lab [CNSL] Computer Engineering Department

What is subnet?

A sub network, or subnet, is a logical, visible subdivision of an IP network. The practice of dividing
a network into two or more networks is called sub netting. Computers that belong to a subnet are
addressed with a common identical, most-significant bit-group in their IP. This results in the
logical division of an IP address into two fields, a network or routing prefix and the rest field or
host identifier. The rest field is an identifier for a specific host or network interface.

For the purpose of network management, an IP address is divided into two logical parts, the
network prefix and the host identifier or rest field. All hosts on a sub network have the same
network prefix. This routing prefix occupies the most-significant bits of the address. The number
of bits allocated within a network to the internal routing prefix may vary between subnets,
depending on the network architecture. While in IPv6 the prefix must consist of a set of contiguous
1-bits, in IPv4 this is not enforced, though there is no advantage to using noncontiguous 1-bits.
The host part is a unique local identification and is either a host number on the local network or
an interface identifier.

What is subnet masking?

An IP address has two components, the network address and the host address. A subnet mask
separates the IP address into the network and host addresses (<network><host>). Subnetting
further divides the host part of an IP address into a subnet and host address

SIT, Lonavala. Page 29


Computer Network & Security Lab [CNSL] Computer Engineering Department

(<network><subnet><host>) if additional sub network is needed. It is called a subnet mask


because it is used to identify network address of an IP address by performing a bitwise AND
operation on the net mask.

A Subnet mask is a 32-bit number that masks an IP address, and divides the IP address into network
address and host address. Subnet Mask is made by setting network bits to all "1"s and setting host
bits to all "0"s. Within a given network, two host addresses are reserved for special purpose, and
cannot be assigned to hosts. The "0" address is assigned a network address and "255" is assigned
to a broadcast address, and they cannot be assigned to hosts.

A mask used to determine what subnet an IP address belongs to. An IP address has two
components, the network address and the host address.

For example:

Consider the IP address 150.215.017.009. Assuming this is part of a Class B network, the first
two numbers (150.215) represent the Class B network address, and the second two numbers
(017.009) identify a particular host on this network.

Subnetting an IP network is to separate a big network into smaller multiple networks for
reorganization and security purposes. All nodes (hosts) in a sub network see all packets transmitted
by any node in a network. Performance of a network is adversely affected under heavy traffic load
due to collisions and retransmissions.

Applying a subnet mask to an IP address separates network address from host address. The network
bits are represented by the 1's in the mask, and the host bits are represented by 0's. Performing a
bitwise logical AND operation on the IP address with the subnet mask produces the network
address.

Write a program to demonstrate Sub-netting and find subnet masks import java.io.*; import
java.net.InetAddress; class subnet1 {

SIT, Lonavala. Page 30


Computer Network & Security Lab [CNSL] Computer Engineering Department

public static void main(String[] args) throws IOException {

System.out.println("ENTER IP:");
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String ip = br.readLine();
String checkclass = ip.substring(0, 3);

int cc = Integer.parseInt(checkclass);
String mask = null;
if(cc>0)
{
if(cc<=127)
{
mask = "255.0.0.0";
System.out.println("Class A IP Address");
System.out.println("SUBNET MASK:\n"+mask);
}
if(cc>=128 && cc<=191)
{
mask = "255.255.0.0";
System.out.println("Class B IP Address");
System.out.println("SUBNET MASK:\n"+mask);
}
if(cc>=192 && cc<=223)
{
mask = "255.255.255.0";
System.out.println("Class C IP Address");
System.out.println("SUBNET MASK:\n"+mask);
}
if(cc>=224 && cc<=239)
{
mask = "255.0.0.0";
System.out.println("Class D IP Address Used for multicasting");
}
if(cc>=240 && cc<=254)
{
mask = "255.0.0.0";
System.out.println("Class E IP Address Experimental Use");
}
}

String networkAddr="";
String lastAddr="";
String[] ipAddrParts=ip.split("\\.");
String[] maskParts=mask.split("\\.");

SIT, Lonavala. Page 31


Computer Network & Security Lab [CNSL] Computer Engineering Department

for(int i=0;i<4;i++){ int


x=Integer.parseInt(ipAddrParts[i]); int
y=Integer.parseInt(maskParts[i]);
int z=x&y; networkAddr+=z+"."; int
w=z|(y^255);
lastAddr+=w+".";
}

System.out.println("First IP of block: "+networkAddr);


System.out.println("Last IP of block: "+lastAddr);
}

C:\Users\Hitesh>d:

D:\>cd program

D:\program>cd "java programming"

D:\program\java programming>javac subnet1.java

D:\program\java programming>java subnet1 ENTER IP:


164.40.1.1 Class B IP Address
SUBNET MASK:
255.255.0.0
First IP of block: 164.40.0.0.
Last IP of block: 164.40.255.255.

CONCLUSION: - Thus we have implemented subnetting program.

SIT, Lonavala. Page 32


Computer Network & Security Lab [CNSL] Computer Engineering Department

Experiment No-06

AIM: Write a program to implement link state /Distance vector routing protocol to find suitable
path for transmission.

OBJECTIVES:

• To study TCP protocol.


• To implement socket programming.
• To use TCP socket for wired network.

PROBLEM STATMENT:

Write a program to implement link state /Distance vector routing protocol to find suitable path for
transmission.

OUTCOMES:

CO2: Analyze data flow between peer to peer in an IP network using Application, Transport and
Network Layer Protocols

SOFTWARE & HARDWARE REQUIREMENTS:

• Software: gcc compiler & wireshark.

• Hardware: Open source Linux operating system

THEORY:

A distance-vector routing (DVR) protocol requires that a router inform its neighbors of topology
changes periodically. Historically known as the old ARPANET routing algorithm (or known as
Bellman-Ford algorithm).
Bellman Ford Basics – Each router maintains a Distance Vector table containing the distance
between itself and ALL possible destination nodes. Distances, based on a chosen metric, are
computed using information from the neighbors’ distance vectors.

Distance Vector Algorithm –

1. A router transmits its distance vector to each of its neighbors in a routing packet.

SIT, Lonavala. Page 33


Computer Network & Security Lab [CNSL] Computer Engineering Department

2. Each router receives and saves the most recently received distance vector from each of its
neighbors.
3. A router recalculates its distance vector when:
• It receives a distance vector from a neighbor containing different information than
before.
• It discovers that a link to a neighbor has gone down.

• From time-to-time, each node sends its own distance vector estimate to neighbors.
When a node x receives new DV estimate from any neighbor v, it saves v’s
distance vector and it updates its own DV using B-F equation:
• Dx(y) = min { C(x,v) + Dv(y), Dx(y) } for each node y N
Example – Consider 3-routers X, Y and Z as shown in figure. Each router have their routing
table. Every routing table will contain distance to the destination nodes.

Consider router X , X will share it routing table to neighbors and neighbors will share it routing
table to it to X and distance from node X to destination will be calculated using bellmen- ford
equation.
Dx(y) = min { C(x,v) + Dv(y)} for each node y N

SIT, Lonavala. Page 34


Computer Network & Security Lab [CNSL] Computer Engineering Department

As we can see that distance will be less going from X to Z when Y is intermediate node(hop) so
it will be update in routing table X.

Similarly for Z also –

SIT, Lonavala. Page 35


Computer Network & Security Lab [CNSL] Computer Engineering Department

Finally the routing table for all –

SIT, Lonavala. Page 36


Computer Network & Security Lab [CNSL] Computer Engineering Department

Advantages of Distance Vector routing –


It is simpler to configure and maintain than link state routing.
Disadvantages of Distance Vector routing –
It is slower to converge than link
state.
• It is at risk from the count-to-infinity problem.
• It creates more traffic than link state since a hop count change must be propagated
to all routers and processed on each router. Hop count updates take place on a
periodic basis, even if there are no changes in the network topology, so
bandwidth-wasting broadcasts still occur.
• For larger networks, distance vector routing results in larger routing tables than
link state since each router must know about all other routers. This can also lead
to congestion on WAN links.

SIT, Lonavala. Page 37


Computer Network & Security Lab [CNSL] Computer Engineering Department

Write a program to implement link state /Distance vector routing protocol to find suitable path
for transmission.

#include<stdlib.h>
#include<stdio.h>
#define NUL 1000 #define NODES 10
struct node
{
int t[NODES][3];
};
struct node n[NODES]; typedef struct node NOD;
int main()
{
void init(int,int); void inp(int,int); void
caller(int,int); void op1(int,int,int); void
find(int,int);
int i,j,x,y,no; do{
printf("\n Enter the no of nodes required:");
scanf("%d",&no); }while(no>10||no<0); for(i=0;i<no;i++)
{ init(no,i); inp(no,i);
}
printf("\nThe configuration of the nodes after initalization is as follows:"); for(i=0;i<no;i++) op1(no,i,0);
for(j=0;j<no;j++)
{
for(i=0;i<no;i++)
caller(no,i);
}
printf("\nThe config of the nodes after the comp of the paths is as follows:"); for(i=0;i<no;i++) op1(no,i,1); while(1)
{ printf("\n Enter 0 to exit or any other key to find the shortest path:"); scanf("%d",&j); if(!j) break; Do{
printf("\n Enter the nodes btn which path is to be found:"); scanf("%d%d",&x,&y);
}while((x<0||x>no) && (y<0||y>no));
printf("\nThe most suitable route from node %d to %d is as follows\n",x,y); find(x,y); printf("%d",y);
printf("\nThe length of the shortest path between node %d & %d is %d",x,y,n[x1].t[y-
1][2]); }
}
void init(int no,int x)
{
int i; for(i=0;i999); if(n[x].t[i][2]!=999) n[x].t[i][3]=i; }
}}
void caller(int no,int x) { void compar(int,int,int); int i; for(i=0;iz) { n[x].t[i][2]=z; n[x].t[i][3]=y; }
}
}
void op1(int no,int x,int z)
{ int i,j;
printf("\n The routing table for node no %d is as follows",x+1);
printf("\n\n\t\t\tDESTINATION\tDISTANCE\tNEXT_HOP"); for(i=0;i=999) ||(n[x].t[i][2]>=(999*no)))
printf("\n\t\t\t %d \tNO LINK \t NO HOP",n[x].t[i][1]+1); else if(n[x].t[i][3]==NUL)
printf("\n\t\t\t %d \t\t %d \t\t NO HOP",n[x].t[i][1]+1,n[x].t[i][2]); else
printf("\n\t\t\t %d \t\t %d \t\t%d",n[x].t[i][1]+1,n[x].t[i][2],n[x].t[i][3]+1); } }
void find(int x,int y) COMPUTER NETWORKS LABORATORY { int i,j; i=x-1; j=y-1; printf("%d->",x);
if(n[i].t[j][3]!=j) { find(n[i].t[j][3]+1,y); return; } }

SIT, Lonavala. Page 38


Computer Network & Security Lab [CNSL] Computer Engineering Department

CONCLUSION: - Hence, we learn distance vector routing protocol.

SIT, Lonavala. Page 39


Computer Network & Security Lab [CNSL] Computer Engineering Department

Experiment No-07

AIM: To implement of socket programming for TCP using C.

OBJECTIVES:
• To study TCP protocol.
• To implement socket programming.
• To use TCP socket for wired network.

PROBLEM STATMENT:

Write a program using TCP socket for wired network for following a.
Say Hello to Each other
b. File transfer
c. Calculator

OUTCOMES:

CO5: Demonstrate TCP & UDP Protocol.

SOFTWARE & HARDWARE REQUIREMENTS:

• Software: gcc compiler & wireshark.

• Hardware: Open source Linux operating system

THEORY:

TCP:
The Transmission Control Protocol provides a communication service at an intermediate level
between an application program and the Internet Protocol. It provides host-to-host connectivity at
the Transport Layer of the Internet model.

The client server model

SIT, Lonavala. Page 40


Computer Network & Security Lab [CNSL] Computer Engineering Department

Most intercrosses communication uses the client server model. These terms refer to the two
processes which will be communicating with each other. One of the two processes, the client,
connects to the other process, the server, typically to make a request for information. A socket is
one end of an intercrosses communication channel. The two processes each establish their own
socket.

SERVER SOCKET METHODS


Sr.No. Method & Description

1 s.bind()This method binds address (hostname, port number pair) to socket.

2 s.listen()This method sets up and start TCP listener.

3 s.accept()This passively accept TCP client connection, waiting until connection


arrives (blocking).

CLIENT SOCKET METHODS


Sr.No. Method & Description

1 s.connect()This method actively initiates TCP server connection.

GENERAL SOCKET METHODS


Sr.No. Method & Description

1 s.recv()This method receives TCP message

2 s.send()This method transmits TCP message

SIT, Lonavala. Page 41


Computer Network & Security Lab [CNSL] Computer Engineering Department

3 s.recvfrom()This method receives UDP message

4 s.sendto()This method transmits UDP message

5 s.close()This method closes socket

6 socket.gethostname()Returns the hostname.

The steps involved in establishing a socket on the client side are as follows:

1. Create a socket with the socket( ) system call

2. Connect the socket to the address of the server using the connect( ) system call

3. Send and receive data. There are a number of ways to do this, but the simplest is to use the
read ( ) and write ( ) system calls.
4. Accept a connection with the accept ( ) system call. This call typically blocks until a client
connects with the server.

5. Send and receive data

SIT, Lonavala. Page 42


Computer Network & Security Lab [CNSL] Computer Engineering Department

FTP:

The File Transfer Protocol (FTP) is a standard network protocol used to transfer computer files
from one host to another host over a TCP-based network, such as the Internet. FTP is built on
client-server architecture and uses separate control and data connections between the client and
the server. FTP users may authenticate themselves using a clear-text sign-in protocol, normally in
the form of a username and password, but can connect anonymously if the server is configured to
allow it. For secure transmission that protects the username and password, and encrypts the
content, FTP is often secured with SSL/TLS (FTPS).

Communication and data transfer:

FTP may run in active or passive mode, which determines how the data connection is established.
In both cases, the client creates a TCP control connection from a random unprivileged port N to
the FTP server command port 21. In active modes, the client starts listening for incoming data
connections on port N+1 from the server (the client sends the FTP command PORT N+1 to inform
the server on which port it is listening). In situations where the client is behind a firewall and
unable to accept incoming TCP connections, passive mode may be used. In this mode, the client
SIT, Lonavala. Page 43
Computer Network & Security Lab [CNSL] Computer Engineering Department

uses the control connection to send a PASV command to the server and then receives a server IP
address and server port number from the server, which the client then uses to open a data
connection from an arbitrary client port to the server IP address and server port number received.
Both modes were updated in September 1998 to support IPV6. Further changes were introduced
to the passive mode at that time, updating it to extended passive mode.

The server responds over the control connection with three-digit status codes in ASCII with an
optional text message. The numbers represent the code for the response and the optional text
represents a human-readable explanation or request. An ongoing transfer of file data over the data
connection can be aborted using an interrupt message sent over the control connection.

Login
FTP login utilizes a normal username and password scheme for granting access. The username is
sent to the server using the USER command, and the password is sent using the PASS command.
If the information provided by the client is accepted by the server, the server will send a greeting
to the client and the session will commence.
Anonymous FTP
A host that provides an FTP service may provide anonymous FTP access. Users typically log into
the service with an 'anonymous' (lower-case and case-sensitive in some FTP servers) account when
prompted for user name. Although users are commonly asked to send their email address instead
of a password, no verification is actually performed on the supplied data.

SIT, Lonavala. Page 44


Computer Network & Security Lab [CNSL] Computer Engineering Department

Write a program using TCP socket for wired network for following a.
Say Hello to Each other b. File transfer c. Calculator
// Hello Client Side

#include<sys/types.h>

#include<sys/socket.h>
#include<stdio.h>

#include<stdlib.h>
#include<string.h>
#include<netinet/in.h>

#include<arpa/inet.h>
#include<stdlib.h>
#define buffsize 150

int main(void)
{
struct sockaddr_in clientaddr;

char recvline[buffsize]; int sockfd,n;

if((sockfd=socket(AF_INET,SOCK_STREAM,0))<0)

perror("Socket Creation Error.\n"); else

printf("Socket Created Successfully\n"); bzero((char *) &clientaddr,


sizeof(clientaddr)); clientaddr.sin_family=AF_INET;

SIT, Lonavala. Page 45


Computer Network & Security Lab [CNSL] Computer Engineering Department

clientaddr.sin_addr.s_addr=inet_addr("127.0.0.1"); clientaddr.sin_port=htons(54321); if(connect(sockfd,(struct


sockaddr *) &clientaddr, sizeof(clientaddr)) < 0 ) perror("Connect error\n");
else
printf("Connected successfully\n");
while(( n = read(sockfd,recvline,buffsize)) > 0 )
{
recvline[n]=0;
if(fputs(recvline,stdout)==EOF)
perror("fputs Error.\n");
} if(n < 0)
perror("Read Error\n");
exit(0);
}

Hello server:
// Hello Server-Side Program

#include<sys/types.h>
#include<sys/socket.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<netinet/in.h>
#include<stdlib.h>

#define buffsize 150

int main(void)
{
struct sockaddr_in servaddr,clientaddr; char
buff[buffsize],crcbuff[buffsize]; int listenfd,connfd;
int sin_size;

if((listenfd=socket(AF_INET,SOCK_STREAM,0))==-1) perror("Socket
Creation Error.\n"); else
printf("Socket Created Successfully\n"); bzero((char *) &servaddr,
sizeof(servaddr)); servaddr.sin_family=AF_INET;
servaddr.sin_addr.s_addr=inet_addr("192.168.0.1"); servaddr.sin_port=htons(54321);
if(bind(listenfd, (struct sockaddr *)&servaddr,sizeof(servaddr)) == -1)
perror("Bind Error\n");
listen(listenfd,4);
sin_size = sizeof(struct sockaddr_in);
for(;;)
{
if((connfd=accept(listenfd,(struct sockaddr *)&clientaddr,
&sin_size))==-1)

SIT, Lonavala. Page 46


Computer Network & Security Lab [CNSL] Computer Engineering Department

perror("Accept Error\n"); strcpy(buff,"Hello Client -


Server\n");
write(connfd,buff,strlen(buff)); close(connfd);
}
}

Echo.client:
#include<stdio.h>
#include<stdlib.h>
#include<error.h>
#include<string.h>
#include<netdb.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<sys/socket.h>
#include<sys/wait.h>
#define PORT 54321 /*well know port */ /* 55*/
#define MAXLINE 100 /* how many pending connection queue will hold */ void str_cli(FILE *fp, int sockfd)
{
char sendline[MAXLINE], recvline[MAXLINE]; int i;
while(fgets(sendline,MAXLINE,fp) != NULL)
{
for(i=0;i<100;i++)
recvline[i]='\0';
write(sockfd,sendline, strlen(sendline)); if
(read(sockfd,recvline,MAXLINE)==0)
perror("server terminated prematurely");
fputs(recvline,stdout);
}
}

int main (int argc,char* argv[])


{
int sockfd; struct sockaddr_in their_addr;
struct sockaddr_in my_addr;
if (argc != 2)
{
fprintf(stderr, "usage:client <hostname>\n");
exit(1);
}

if ((sockfd = socket (AF_INET, SOCK_STREAM ,0))==-1)


{
perror("socket"); exit(1);
}
my_addr.sin_family= AF_INET; my_addr.sin_port= htons(PORT);
bzero(&(my_addr.sin_zero),8);
inet_pton(AF_INET, argv[1], &my_addr.sin_addr);
if (connect (sockfd, (struct sockaddr *)&my_addr,sizeof(struct sockaddr)) == -1)
{

SIT, Lonavala. Page 47


Computer Network & Security Lab [CNSL] Computer Engineering Department

perror("connect"); exit(1);
printf("Enter the data \n");
}
str_cli(stdin, sockfd);
exit(0);
}

Echo server.c
#include <stdio.h>
#include <stdlib.h>
#include <error.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/wait.h>

#define MYPORT 54321 /*well know port */ /*55*/


#define BACKLOG 10 /* how many pending connection queue will hold */ #define
MAXLINE 100
void str_echo(int sockfd)
{ int n,i;
char line[MAXLINE];
for ( ; ; )
{
for(i=0;i<100;i++)
line[i]='\0';
if((n=read(sockfd,line,MAXLINE)) ==0) return;
write(sockfd,line,n);
printf ("client line was: %s\n", line);
}
}
main()
{
int sockfd , new_fd ; /* listen on sock_fd ,new connection on new_fd */ struct sockaddr_in my_addr;
/* my address */ struct sockaddr_in their_addr; int clilen;
int childpid;
if ((sockfd = socket (AF_INET, SOCK_STREAM ,0))==-1)
{
perror("soket"); exit(1);
}
my_addr.sin_family= AF_INET; my_addr.sin_port= htons(MYPORT);
my_addr.sin_addr.s_addr= htonl(INADDR_ANY);
bzero(&(my_addr.sin_zero),8);
if (bind(sockfd, (struct sockaddr *)&my_addr,sizeof(struct sockaddr)) == -1){
perror("bind");
exit(1);
}
if(listen(sockfd,BACKLOG) == -1) {
perror("listen");

SIT, Lonavala. Page 48


Computer Network & Security Lab [CNSL] Computer Engineering Department

exit(1); } for( ; ; )
{
clilen = sizeof(their_addr);
if ((new_fd =accept(sockfd, (struct sockaddr*)&their_addr,&clilen)) == -1)
{
perror("accept");
continue;
}
if ( ( childpid = fork() ) == 0)
{
close(sockfd); str_echo(new_fd);
exit(0);
}
close(new_fd);
}
}
*OUTPUT CLIENT
iotlab@iotlab-Veriton-M200-B360:~$ cd TCP\ Socket/ iotlab@iotlab-Veriton-M200-B360:~/TCP Socket$ cd Simple\ Hello/
iotlab@iotlab-Veriton-M200-B360:~/TCP Socket/Simple Hello$ gcc client_simple_hello.c -o client client_simple_hello.c: In
function ‘main’: client_simple_hello.c:23:30: warning: implicit declaration of function ‘inet_addr’; did you mean
‘s6_addr’? [-Wimplicit-function-declaration] serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
^~~~~~~~~ s6_addr
iotlab@iotlab-Veriton-M200-B360:~/TCP Socket/Simple Hello$ ./client
Data received: Hello World

OUTPUT SERVER
iotlab@iotlab-Veriton-M200-B360:~/TCP Socket/Simple Hello$ gcc server_simple_hello.c -o server server_simple_hello.c: In function ‘main’:
server_simple_hello.c:24:30: warning: implicit declaration of function ‘inet_addr’; did you mean ‘s6_addr’?
[-Wimplicit-function-declaration]
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
^~~~~~~~~ s6_addr
iotlab@iotlab-Veriton-M200-B360:~/TCP Socket/Simple Hello$ ./server Listening
*/ /*OUTPUT
SERVER
iotlab@iotlab-Veriton-M200-B360:~$ cd TCP\ Socket/ iotlab@iotlab-Veriton-M200-B360:~/TCP Socket$ cd File\ Transfer/
iotlab@iotlab-Veriton-M200-B360:~/TCP Socket/File Transfer$ gcc Server_file.c -o server
iotlab@iotlab-Veriton-M200-B360:~/TCP Socket/File Transfer$ ./server
Socket retrieve success
Bytes read 0
End of file

OUTPUT CLIENT
iotlab@iotlab-Veriton-M200-B360:~/TCP Socket/File Transfer$ gcc Client_file.c -o client iotlab@iotlab-Veriton-M200-B360:~/TCP Socket/File
Transfer$ ./clientiotlab@iotlab-Veriton-M200-
B360:~/TCP Socket/File Transfer$

CONCLUSION: - Thus we have successfully implemented the socket programming for TCP using C.

SIT, Lonavala. Page 49


Computer Network & Security Lab [CNSL] Computer Engineering Department

Experiment No 08

AIM: To implement UDP socket to enable file transfer.

OBJECTIVES:
• To study UDP protocol.
• To implement socket programming.
• To transfer files using UDP socket.

PROBLEM STATMENT:

Write a program using UDP Sockets to enable file transfer (Script, Text, Audio and Video one
file each) between two machines. Demonstrate the packets captured traces using Wireshark
Packet Analyzer Tool for peer to peer mode.

OUTCOMES:

CO5: Demonstrate TCP & UDP Protocol.

SOFTWARE & HARDWARE REQUIREMENTS:

• Software: gcc compiler

• Hardware: Open source Linux operating system.

THEORY:

UDP:

UDP (User Datagram Protocol) is a communication protocol that offers a limited amount of service
when messages are exchanged between computers in a network that uses the Internet Protocol (IP).
UDP is an alternative to the Transmission Control Protocol (TCP) and, together with IP, is
sometimes referred to as UDP/IP. Like the Transmission Control Protocol, UDP uses the Internet
Protocol to actually get a data unit (called a datagram) from one computer to another. Unlike TCP,
however, UDP does not provide the service of dividing a message into packets (datagrams) and
reassembling it at the other end. Specifically, UDP doesn't provide sequencing of the packets that

SIT, Lonavala. Page 50


Computer Network & Security Lab [CNSL] Computer Engineering Department

the data arrives in. This means that the application program that uses UDP must be able to make
sure that the entire message has arrived and is in the right order. Network applications that want
to save processing time because they have very small data units to exchange (and therefore very
little message reassembling to do) may prefer UDP to TCP. The Trivial File Transfer Protocol
(TFTP) uses UDP instead of TCP.
With a UDP socket a connection is NOT made, instead the sender just issues a message to its
destination and hopes it gets there! The message uses a datagram of fixed length, often termed a
record. Since there is no connection between client and server the client can send a datagram to
one server and then immediately send a datagram to another server using the same socket UDP is
a connectionless protocol.
Trivial File Transfer Protocol (TFTP) is a simple, lock-step, file transfer protocol which allows a
client to get from or put a file onto a remote host.
TFTP is a simple protocol for transferring files, implemented on top of the UDP/IP protocols
using IANA registered port number 69. TFTP was designed to be small and easy to implement,
And therefore it lacks most of the advanced features offered by more robust file transfer
protocols.

SIT, Lonavala. Page 51


Computer Network & Security Lab [CNSL] Computer Engineering Department

Write a program using UDP Sockets to enable file transfer (Script, Text, Audio and
Video one file each) between two machines.

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<arpa/inet.h>
#include<sys/socket.h>

#define SERVER "127.0.0.1"


#define BUFLEN 503
#define PORT 8885

void die(char *s)


{
perror(s);
exit(1);
}
unsigned long fsize(char* file)
{
FILE * f = fopen(file, "r"); fseek(f, 0, SEEK_END);
unsigned long len = (unsigned long)ftell(f); fclose(f); return
len;
}

int main(void)
{
struct sockaddr_in si_other; int s, i,
slen=sizeof(si_other); char buf[BUFLEN];
char message[BUFLEN];

if ( (s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)


{
die("socket");
}

memset((char *) &si_other, 0, sizeof(si_other));


si_other.sin_family = AF_INET;
si_other.sin_port = htons(PORT);

if (inet_aton(SERVER , &si_other.sin_addr) == 0)
{
fprintf(stderr, "inet_aton() failed\n");
exit(1);
}
//memset(message,0,503);
char fname[20];
printf("Enter Filename with extension: ");
scanf("%s",&fname);

SIT, Lonavala. Page 52


Computer Network & Security Lab [CNSL] Computer Engineering Department

sendto(s, fname, 20 , 0 , (struct sockaddr *) &si_other, slen); /*if (sendto(s, message, 20 , 0 ,


(struct sockaddr *) &si_other, slen)==-1)
{
die("sendto()");
}*/
memset(message,0,503);
//unsigned long siz = fsize("mysiren.mp3"); unsigned long siz = fsize(fname);
printf("%ld",(siz % 503)); char str[10]; sprintf(str, "%d", siz); sendto(s, str, 20 , 0 ,
(struct sockaddr *) &si_other, slen); /*if (sendto(s, str, 20 , 0 , (struct sockaddr *) &si_other,
slen)==-1)
{
die("sendto()");
}*/
//char buffer[100];
FILE *f;
//f=fopen("mysiren.mp3","rb"); f=fopen(fname,"rb");
memset(message,0,503); fread(message, 503,1,f); //while(!feof(f)){ int itr
=1; while(itr*503<siz){
//fread(message, 503,1,f);
if (sendto(s, message, 503 , 0 , (struct sockaddr *) &si_other, slen)==-1)
{
die("sendto()");
}
memset(message,0,503); fread(message,
503,1,f);
itr++;
}
fread(message, (siz % 503),1,f); sendto(s, message, (siz % 503) , 0 , (struct sockaddr *) &si_other,
slen); /*if (sendto(s, message, 503 , 0 , (struct sockaddr *) &si_other, slen)==-1)
{
die("sendto()");
}*/
memset(message,0,503); fclose(f);
close(s);
//shutdown(s, SHUT_WR);
return 0;
}

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<arpa/inet.h>
#include<sys/socket.h>

#define BUFLEN 503


#define PORT 8885

void die(char *s)


{
perror(s);

SIT, Lonavala. Page 53


Computer Network & Security Lab [CNSL] Computer Engineering Department

exit(1);
}

int main(void)
{
struct sockaddr_in si_me, si_other;

int s, i,j, slen = sizeof(si_other) , recv_len;


char buf[BUFLEN];

if ((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)


{
die("socket");
}

memset((char *) &si_me, 0, sizeof(si_me));

si_me.sin_family = AF_INET; si_me.sin_port = htons(PORT);


si_me.sin_addr.s_addr = htonl(INADDR_ANY);

if( bind(s , (struct sockaddr*)&si_me, sizeof(si_me) ) == -1)


{
die("bind");
}
//memset(buf,0,503); char
fname[20]; FILE *fp;
recv_len = recvfrom(s, buf, 20, 0, (struct sockaddr *) &si_other, &slen);
/*if ((recv_len = recvfrom(s, fname, 20, 0, (struct sockaddr *) &si_other,
&slen)) == 1)
{
die("recvfrom()");
}*/
char fna[100];
//strcpy(fna,"/home/krishna/ftp new/"); //replace krishna by current
username
//strcat(buf,"_new");

//printf("%s",fname);
memset(buf,0,503);
recv_len = recvfrom(s, buf, 20, 0, (struct sockaddr *) &si_other, &slen);
/*if ((recv_len = recvfrom(s, buf, 20, 0, (struct sockaddr *) &si_other, &slen)) == -1)
{
die("recvfrom()");
}*/
//printf("%s",buf);
strcpy(fna,buf); int len= strlen(fna);
printf("%d",len);
for(j=len-1;j>=0;j--)
{
if(fna[j]=='.')

SIT, Lonavala. Page 54


Computer Network & Security Lab [CNSL] Computer Engineering Department

{
fna[j-1]='1';
}
}
unsigned long mm = atoi(buf); //fp=fopen("ve1.mp4","wb");
//fp=fopen("mysiren1.mp3","wb");

fp=fopen(fna,"wb"); int itr=1;


memset(buf,0,503); while(itr*503<mm)
{
if ((recv_len = recvfrom(s, buf, 503, 0, (struct sockaddr *)
&si_other, &slen)) == -1)
{
die("recvfrom()");
}
fwrite(buf,503, 1, fp);
memset(buf,0,503);
itr++;
}
printf("%d",(mm%503));
recv_len = recvfrom(s, buf, (mm%503), 0, (struct sockaddr *) &si_other,
&slen); /*if ((recv_len = recvfrom(s, buf, (mm%503), 0, (struct sockaddr *)
&si_other, &slen)) == -1)
{
die("recvfrom()");
}*/
fwrite(buf,(mm%503), 1, fp);
memset(buf,0,503); fclose(fp); close(s);
//shutdown(s, SHUT_WR);
return 0;
}

OUTPUT : ad SIT,Lonavala

CONCLUSION: - Thus we have successfully implemented the socket programming for UDP to
enable file transfer (Script, Text, Audio and Video one file each) between two machines

SIT, Lonavala. Page 55


Computer Network & Security Lab [CNSL] Computer Engineering Department

Experiment No-09

AIM: To capture packets using Wireshark, write the exact packet capture filter expressions to
accomplish the following and save the output in file:

OBJECTIVES:

• To analyze packet formats.


• To understand Ethernet, IP, TCP &UDP protocol.
• To study packet capturing.

PROBLEM STATMENT:

Write a program to analyze following packet formats captured through Wireshark for wired
network. 1. Ethernet 2. IP 3.TCP 4. UDP

OUTCOMES:

CO5: Demonstrate TCP & UDP Protocol.

SOFTWARE & HARDWARE REQUIREMENTS:

• Software: gcc complier and wireshark tool

• Hardware:

THEORY:

Packet sniffer \ Packet analyzer:

A packet analyzer (also known as a network analyzer, protocol analyzer or packet sniffer or for
particular types of networks, an Ethernet sniffer or wireless sniffer) is a computer program or a
piece of computer hardware that can intercept and log traffic passing over a digital network or part
of a network. As data streams own across the network, the sniffer captures each packet and, if
needed, decodes the packet's raw data, showing the values of various fields in the packet, and
analyzes its content according to the appropriate RFC or other specifications.

Different types of packet:

1. TCP:

SIT, Lonavala. Page 56


Computer Network & Security Lab [CNSL] Computer Engineering Department

The Transmission Control Protocol (TCP) is one of the core protocols of the Internet protocol suite
(IP), and is so common that the entire suite is often called TCP/IP. TCP provides reliable, ordered
and error-checked delivery (or notification of failure to deliver) of a stream of octets between
programs running on computers connected to a local area network, intranet or the public Internet.
It resides at the transport layer. Web browsers use TCP when they connect to servers on the World
Wide Web, and it is used to deliver email and transfer files from one location to another. The
protocol corresponds to the transport layer of TCP/IP suite. TCP provides a communication service
at an intermediate level between an application program and the Internet Protocol (IP). That is,
when an application program desires to send a large chunk of data across the Internet using IP,
instead of breaking the data into IP-sized pieces and issuing a series of IP requests, the software
can issue a single request to TCP and let TCP handle the IP works by exchanging pieces of
information called packets. A packet is a sequence of octets (bytes) and consists of a header
followed by a body.

The header describes the packet's source, destination and control information. The body contains
the data IP is transmitting. Due to network congestion, traffic load balancing, or other
unpredictable network behavior, IP packets can be lost, duplicated, or delivered out of order. TCP
detects these problems, requests retransmission of lost data, rearranges out-of-order data, and even
helps minimize network congestion to reduce the occurrence of the other problems. If the data still
remains undelivered, its source is notified of this failure. Once the TCP receiver has reassembled
the sequence of octets originally transmitted, it passes them to the receiving application. Thus,
TCP abstracts the application's communication from the underlying networking details. TCP is a
reliable stream delivery service that guarantees that all bytes received will be identical with bytes
sent and in the correct order. Since packet transfer over many networks is not reliable, a technique
known as positive acknowledgment with retransmission is used to guarantee reliability of packet
transfers. This fundamental technique requires the receiver to respond with an acknowledgment
message as it receives the data. The sender keeps a record of each packet it sends. The sender also
maintains a timer from when the packet was sent, and retransmits a packet if the timer expires
before the message has been acknowledged. The timer is needed in case a packet gets lost or
corrupted.

SIT, Lonavala. Page 57


Computer Network & Security Lab [CNSL] Computer Engineering Department

2. UDP:

The User Datagram Protocol (UDP) is one of the core members of the Internet protocol Suite. UDP
uses a simple connectionless transmission model with a minimum of protocol mechanism. It has
no handshaking dialogues, and thus exposes any unreliability of the underlying network protocol
to the user's program. There is no guarantee of delivery, ordering, or duplicate protection. UDP
provides checksums for data integrity, and port numbers for addressing different functions at the
source and destination of the datagram. With UDP, computer applications can send messages, in
this case referred to as datagrams, to other hosts on an Internet Protocol (IP) network without prior
communications to set up special transmission channels or data paths. UDP is suitable for purposes
where error checking and correction is either not necessary or is performed in the application,
avoiding the overhead of such processing at the network interface level. Time-sensitive
applications often use UDP because dropping packets is preferable to waiting for delayed packets,
which may not be an option in a real-time system.

SIT, Lonavala. Page 58


Computer Network & Security Lab [CNSL] Computer Engineering Department

3. ICMP:

The Internet Control Message Protocol (ICMP) is one of the main protocols of the Internet Protocol
Suite. It is used by network devices, like routers, to send error messages indicating, for example,
that a requested service is not available or that a host or router could not be reached.

ICMP can also be used to relay query messages. It is assigned protocol number 1.ICMP differs
from transport protocols such as TCP and UDP in that it is not typically used to exchange data
between systems, nor is it regularly employed by end-user network applications (with the
Exception of some diagnostic tools like ping and trace route). ICMP for Internet Protocol version
4 (IPv4) is also known as ICMPv4. IPv6 has a similar protocol, ICMPv6. The Internet Control
Message Protocol is part of the Internet Protocol Suite, as defined in RFC 792. ICMP messages
are typically used for diagnostic or control purposes or generated in response to errors in IP
operations. ICMP errors are directed to the source IP address of the originating packet.

SIT, Lonavala. Page 59


Computer Network & Security Lab [CNSL] Computer Engineering Department

4. IGMP:

The Internet Group Management Protocol (IGMP) is a communications protocol used by hosts
and adjacent routers on IP networks to establish multicast group memberships. IGMP is an integral
part of IP multicast. IGMP can be used for one-to-many networking applications such as online
streaming video and gaming, and allows more efficient use of resources when supporting these
types of applications. IGMP messages are carried in bare IP packets with IP protocol. There is no
transport layer used with IGMP messaging, similar to the Internet Control Message Protocol.
Membership Queries are sent by multicast routers to determine which multicast addresses are of
interest to systems attached to its network. Routers periodically send General Queries to refresh
the group membership state for all systems on its network. Group-Specific Queries are used for
determining the reception state for a particular multicast address.

SIT, Lonavala. Page 60


Computer Network & Security Lab [CNSL] Computer Engineering Department

Write a program to analyze following packet formats captured through Wireshark for wired
network. 1. Ethernet 2. IP 3.TCP 4. UDP
#include <iostream>
#include<fstream>
#include <iomanip>
#include<string>
using namespace std;

int main()
{
cout << "***** PACKET ANALYZER *****" << endl;
string value, sr_no,time,source,destination,info,protocol,len;
int count=-1,i=0;

int choice;
do
{
ifstream file("data.csv");
//Reinitialize Counters
count=-1;

SIT, Lonavala. Page 61


Computer Network & Security Lab [CNSL] Computer Engineering Department

i=0;
cout<<"\nEnter which protocol packets you want to see"<<endl;
cout<<"1.IP\n2.UDP\n3.TCP\n4.Ethernet\n0Exit!!!\nChoice:"<<endl;
cin>>choice;
string protocolChoice; //sting to hold user packet choice
switch(choice){
case 1: protocolChoice="ICMPv6";
break;
case 2: protocolChoice="UDP";
break;
case 3: protocolChoice="TCP";
break;
case 4: protocolChoice="ARP";
break;
default: protocolChoice="ARP";
break;
}
while(file.good()) //LOOP UNTIL FILE HAS CONTENT
{
getline(file,sr_no,','); //GET STRING TILL ,
getline(file,time,',');
getline(file,source,',');
getline(file,destination,',');
getline(file,protocol,',');
getline(file,len,',');
getline(file,info,'\n');

protocol=string(protocol,1,protocol.length()-2);

if(protocol=="Protocol"||protocol==protocolChoice)
{
cout <<setw(4)<<left<<i++;
cout <<setw(12)<<left<< string( time, 1, time.length()-2 );
cout << setw(30)<<left<<string( source, 1, source.length()-2 );
cout << setw(30)<<left<<string( destination, 1, destination.length()-2 );
cout <<setw(8)<<left<<protocol;
cout <<setw(8)<<left<< string( len, 1, len.length()-2 );
cout << string( info, 1, info.length()-2 )<<"\n";
count++;
}
}

SIT, Lonavala. Page 62


Computer Network & Security Lab [CNSL] Computer Engineering Department

file.close();
cout<<"\nTotal Packet Count: "<<count;
}while(choice!=0);
return 0;
}
/* output:
* ***** PACKET ANALYZER *****

Enter which protocol packets you want to see


1.IP
2.UDP
3.TCP
4.Ethernet
0Exit!!!
Choice:
1
Total Packet Count: 34
Enter which protocol packets you want to see
1.IP
2.UDP
3.TCP
4.Ethernet
0Exit!!!
Choice:
2
0 Time Source Destination ProtocolLength Info

Total Packet Count: 0


Enter which protocol packets you want to see
1.IP
2.UDP
3.TCP
4.Ethernet
0Exit!!!
Choice:
3

CONCLUSION:
Hence we have implemented packet formats captured through Wireshark for wired network. 1.
Ethernet 2. IP 3.TCP 4. UDP.

SIT, Lonavala. Page 63


Computer Network & Security Lab [CNSL] Computer Engineering Department

Experiment No 10

AIM: To study DNS lookup.

OBJECTIVES:

• To study DNS lookup.


• To convert IP address to URL and vice-versa.

PROBLEM STATMENT:

Write a program for DNS lookup. Given an IP address input, it should return URL and viceversa

OUTCOMES:

CO2: Analyze data flow between peer to peer in an IP network using Application, Transport and
Network Layer Protocols

SOFTWARE & HARDWARE REQUIREMENTS:

• Software: gcc compiler & python

• Hardware: Open source Linux operating system.

THEORY:

How does a DNS query work? When a DNS client needs to look up a name used in a program, it
queries DNS servers to resolve the name. Each query message the client sends contains three
pieces of information, specifying a question for the server to answer: ... A specified class for the
DNS domain name

Querying DNS. Click the Windows Start button, then "All Programs" and "Accessories."
Rightclick on "Command Prompt" and choose "Run as Administrator." Type "nslookup
%ipaddress%" in the black box that appears on the screen, substituting %ipaddress% with the IP
address for which you want to find the hostname

SIT, Lonavala. Page 64


Computer Network & Security Lab [CNSL] Computer Engineering Department

Instead, you just connect through a domain name server, also called a DNS server or name server,
which manages a massive database that maps domain names toIP addresses. ... The proper term
for this process is DNS name resolution, and you would say that the DNS server resolves the
domain name to the IP address.

Domain Names and IP Addresses. An Internet Protocol, or IP, address is different than a domain
name. The IP address is an actual set of numerical instructions. ... A typical IP address looks like
a string of numbers. It could be 232.17.43.22, for example.
URLs (Uniform Resource Locators) and IP addresses are just identifiers used for this purpose.

The main difference between URL and IP address is what they point to. An IP address basically
points to a computer, whether it is the physical hardware or a virtual one as in the case of shared
hosting

Write a program for DNS lookup. Given an IP address as input, it


should return URL and viceversa

import java.net.*; import java.util.*;

public class IPDemo


{
public static void main(String[] args){
String host;
Scanner ch = new Scanner(System.in);
System.out.print("1.Enter Host Name \n2.Enter IP address \nChoice="); int choice
= ch.nextInt(); if(choice==1)
{
Scanner input = new Scanner(System.in);
System.out.print("\n Enter host name: "); host =
input.nextLine();
try {
InetAddress address = InetAddress.getByName(host);
System.out.println("IP address: " + address.getHostAddress());
System.out.println("Host name : " + address.getHostName());
System.out.println("Host name and IP address: " + address.toString());
}
catch (UnknownHostException ex) {
System.out.println("Could not find " + host);
}
SIT, Lonavala. Page 65
Computer Network & Security Lab [CNSL] Computer Engineering Department

}
else
{
Scanner input = new Scanner(System.in);
System.out.print("\n Enter IP address: "); host =
input.nextLine();
try {
InetAddress address = InetAddress.getByName(host);
System.out.println("Host name : " + address.getHostName());
System.out.println("IP address: " + address.getHostAddress());
System.out.println("Host name and IP address: " + address.toString());

}
catch (UnknownHostException ex) {
System.out.println("Could not find " + host);
} }

}
}

Output : java -cp /tmp/fKKbbtJWHh IPDemo


1.Enter Host Name
2.Enter IP address
Choice=2
Enter IP address: 157.240.18.35
Host name : edge-star-mini-shv-02-ort2.facebook.com
IP address: 157.240.18.35
Host name and IP address: edge-star-mini-shv-02-
ort2.facebook.com/157.240.18.35

CONCLUSION:
Hence we have implemented DNS lookup.

SIT, Lonavala. Page 66


Computer Network & Security Lab [CNSL] Computer Engineering Department

Experiment NO-11

AIM: To Configure RIP/OSPF/BGP using packet tracer.

OBJECTIVES:
• To study RIP/OSPF/BGP protocol.
• To implement packet tracer.
• To Configure RIP/OSPF/BGP.

PROBLEM STATMENT:

Configure RIP/OSPF/BGP using packet Tracer.

OUTCOMES:

CO6: Implement configuration RIP/OSPF/BGP using packet Tracer.

SOFTWARE & HARDWARE REQUIREMENTS:

• Software: Packet tracer tool

• Hardware: Open source Linux operating system, Windows OS

THEORY:

• Configuring RIP requires the following steps:

Step 1: Enable the RIP routing process, which places you in router configuration mode via the
Router#router rip command.

Step 2: Specify those networks that should be advertised using RIP via the Router (config-router)
#network [network-number] command.

SIT, Lonavala. Page 67


Computer Network & Security Lab [CNSL] Computer Engineering Department

Configure OSPF on the R1 Router:

Step 1: Use the router ospf command in global configuration mode to enable OSPF on the R1
router. Enter a process ID of 1 for the process-ID parameter.
R1 (config) #router ospf 1
R1 (config-router) #

Step 2: Configure the network statement for the LAN network.


Once you are in the Router OSPF configuration sub-mode, configure the LAN network 172.16.1.16/28
to be included in the OSPF updates that are sent out of R1.
The OSPF network command uses a combination of network-address and wildcard-mask Similar
to that which can be used by EIGRP. Unlike EIGRP, the wildcard mask in OSPF is Required.
Use an area ID of 0 for the OSPF area-id parameter. 0 will be used for the OSPF area ID in all of the
network statements in this topology.
R1 (config-router) #network 172.16.1.16 0.0.0.15 area 0
R1 (config-router) #

Step 3: Configure the router to advertise the 192.168.10.0/30 network attached to the Serial0/0/0
interface.
R1 (config-router) # network 192.168.10.0 0.0.0.3 area 0
R1 (config-router) #

SIT, Lonavala. Page 68


Computer Network & Security Lab [CNSL] Computer Engineering Department

Step 4: Configure the router to advertise the 192.168.10.4/30 network attached to the Serial0/0/1
interface.
R1 (config-router) # network 192.168.10.4 0.0.0.3 area 0
R1 (config-router) #

Step 5: When you are finished with the OSPF configuration for R1, return to privileged
EXEC mode.
R1 (config-router) #end
%SYS-5-CONFIG_I: Configured from console by console R1#

Configuring BGP requires the following steps:

1(config)#router bgp 1 R1(config- uter)#neighbor 11.0.0.2 remote-


as 2

Use packet Tracer tool for configuration of 3 router network


using one of the following protocol RIP

SIT, Lonavala. Page 69


Computer Network & Security Lab [CNSL] Computer Engineering Department

2. Configure IP addresses on the PCs and the routers.

Router 1

R1(config)#
R1(config)#int fa0/0
R1(config-if)#ip address 10.0.0.1 255.0.0.0
R1(config-if)#no shut

R1(config-if)#
R1(config-if)#int serial 0/0/0
R1(config-if)#ip add 20.0.0.1 255.0.0.0
R1(config-if)#no shut

Router 2

R2(config)#
R2(config)#int fa0/0
R2(config-if)#ip add 30.0.0.1 255.0.0.0
R2(config-if)#no shut

R2(config-if)#
R2(config-if)#int serial 0/0/0
R2(config-if)#ip add 20.0.0.2 255.0.0.0
R2(config-if)#no shut

IP configuration on PCs
Click PC->Desktop->IP Configuration. On each PC assign these addresses:

PC1: IP address: 10.0.0.2 Subnet mask 255.0.0.0 Default Gateway 10.0.0.1 PC2: IP address:

30.0.0.2 Subnet mask 255.0.0.0 Default Gateway 30.0.0.1

And now:

SIT, Lonavala. Page 70


Computer Network & Security Lab [CNSL] Computer Engineering Department

3. Configure RIPv2 on the routers

Router 1

R1(config)#

R1(config)#router rip
R1(config-router)#version 2
R1(config-router)#network 10.0.0.0
R1(config-router)#network 20.0.0.0

Router 2

R2(config)#

R2(config)#router rip
R2(config-router)#version 2
R2(config-router)#network 20.0.0.0
R2(config-router)#network 30.0.0.0

CONCLUSION:
Hence we have implemented configuration of RIP/OSPF/BGP using packet tracer.

SIT, Lonavala. Page 71


Computer Network & Security Lab [CNSL] Computer Engineering Department

Experiment No 12

AIM: Study and analyse the performance of HTTP, HTTPS and FTP protocol using Packet tracer
tool.

OBJECTIVES:

• To study TCP socket programming.


• To implement Peer to Peer chat & Multiuser chat

PROBLEM STATMENT:

OUTCOMES:

CO4: Develop Client-Server architectures and prototypes by the means of correct standards and
technology.

SOFTWARE & HARDWARE REQUIREMENTS:

• Software: gcc compiler, jdk.

• Hardware: Open source Linux operating system

THEORY:

The File Transfer Protocol (FTP) is a standard network protocol used for the transfer of
computer files between a client and server on a computer network.

FTP employs a client-server architecture whereby the client machine has an FTP client
installed and establishes a connection to an FTP server running on a remote machine. After
the connection has been established and the user is successfully authenticated, the data
transfer phase can begin.

Worth noting: Although FTP does support user authentication, all data is sent in clear text,
including usernames and passwords. For secure transmission that protects the username

SIT, Lonavala. Page 72


Computer Network & Security Lab [CNSL] Computer Engineering Department

and password, and encrypts the content, FTP is often secured with SSL/TLS (FTPS) or
replaced with SSH File Transfer Protocol (SFTP).

Let’s now do FTP configuration in Packet Tracer:

1.Build the network topology.

FTP topology.PNG

2. Configure static IP addresses on the Laptop and the server.

Laptop: IP address: 192.168.1.1 Subnet Mask: 255.255.255.0

Server: IP address: 192.168.1.2 Subnet Mask: 255.255.255.0

3. Now try using an FTP client built in the Laptop to send files to an FTP server configured in
the Server.

From the Laptop’s command prompt, FTP the server using the server IP address by typing:
ftp 192.168.1.2

Provide the username(cisco) and password(cisco) [which are the defaults] for ftp login.

SIT, Lonavala. Page 73


Computer Network & Security Lab [CNSL] Computer Engineering Department

ftp from laptop.PNG

You are now in the FTP prompt .

PC0 has an FTP client which can be used to read, write, delete and rename files present in
the FTP server.

The FTP server can be used to read and write configuration files as well as IOS images.
Additionally, the FTP server also supports file operations such rename, delete and listing
directory.

With that in mind, we can do something extra. So let’s do this:

4. Create a file in the Laptop then upload it to the server using FTP.

To do this, open the Text Editor in the Laptop, create a file and give it your name of choice.

Type any text in the editor then save your file. e.g. myFile.txt.

5. Now upload the file from the Laptop to the server using FTP. (An FTP connection has to
be started first. But this is what we’ve done in step 3)

So to do an FTP upload, we’ll type:

put MyFile.txt

SIT, Lonavala. Page 74


Computer Network & Security Lab [CNSL] Computer Engineering Department

put MyFile to FTP directory.PNG

6. Once file upload is successful, go to the Server FTP directory to verify if the file sent has
been received . To do this, go to Server-> Services->FTP. Here look for MyFile.txt sent from
the laptop.

MyFile.txt really send to sever.PNG

SIT, Lonavala. Page 75


Computer Network & Security Lab [CNSL] Computer Engineering Department

Something extra: To check other FTP commands supported by the FTP client running on the
Laptop(or PC), you can use a question mark (?) on the Laptop’s command prompt as shown
below:

All FTP commands supported

You can see the put command that we used to upload our file to the FTP server. Other

commands listed include: get-used to get(download) a file from the server. For example: get

MyFile.txt delete– to delete a file in the FTP directory with the server

For example: delete MyFile.txt

Rename– used to Rename a file cd

– used to change directory.

For example, we can open an HTTP directory in the server by typing: cd /http. This will
change the current directory from FTP directory to HTTP directory

Once the http directory is open, you can upload a file to the HTTP server. You’re now
uploading a file to an HTTP folder(directory) using FTP.

For example: put MyFile.txt

To see this working, let’s open an HTTP directory and upload(put) a file to it using FTP:

changing directory then put files to HTTP directory using FTP

You can now check up in the HTTP directory in the server and verify that the file uploaded
from the Laptop(MyFile.txt) is well received:

SIT, Lonavala. Page 76


Computer Network & Security Lab [CNSL] Computer Engineering Department

MyFile.txt really send to HTTP server

Notice that we are uploading files to an HTTP Server directory using File Transfer
Protocol.(FTP). This is what actually happens when you use an FTP client such as FileZilla
client to upload files to a website. In our case here, we are using an FTP client built-in the
Laptop.

This may interest you: The first FTP client applications were command-line programs
developed before operating systems had graphical user interfaces, and are still shipped with
most Windows and Linux operating systems. (Actually this is what we have been using this
far). Many FTP clients(e.g. FileZilla) and automation utilities have since been developed for
desktops, servers, mobile devices, and hardware. FTP has also been incorporated into
productivity applications, such as HTML editors.

We’ll create an html file in our Laptop, upload it to HTTP server directory using FTP, then
try to access the file from the Laptop’s browser.

On the Laptop, open the text editor, then type some markup(html) and save the file with the
extension .html. See all this below:

SIT, Lonavala. Page 77


Computer Network & Security Lab [CNSL] Computer Engineering Department

File2 HTML code

Save your file as an html file like this:

SIT, Lonavala. Page 78


Computer Network & Security Lab [CNSL] Computer Engineering Department

File2 html.PNG

Now upload the file( File2.html) to the HTTP server using FTP. This is easy. We’ve already
done it previously!

If you’re already in the HTTP directory, you just need to type: put File2.html. If no, first ftp
the server(ftp 192.168.1.2), provide the login username(cisco) and password(cisco); change
the current directory to HTTP(cd /http) , and finally upload the html file onto the HTTP
directory(put File2.html)

Sending File2. html to HTTP directory.PNG

Check whether the html file uploaded has been received in the HTTP directory:

Go to Server->Services-> HTTP. Then look up for the file in the File Manager.

SIT, Lonavala. Page 79


Computer Network & Security Lab [CNSL] Computer Engineering Department

File2 HTML really uploaded into HTTP directory.PNG

Now edit index.html file in the HTTP directory so as to include a link to File2 that we’ve just
uploaded. This will make File2 accessible from the Laptop’s browser. To do this, locate
index.html then click edit. Proceed to edit it as shown below. Then save and accept
overwrite.Index.html editing to include File2 html.PNG

SIT, Lonavala. Page 80


Computer Network & Security Lab [CNSL] Computer Engineering Department

Finally, try to access the newly uploaded file from the Laptop’s browser.

So go to the Laptop’s browser and access the server using the server’s IP address. By doing
this, the browser is making an http request to the server. The server will respond to the
Laptop with the index.html file containing a link to File2 which we’ve uploaded from the
Laptop using FTP.

Http response with File2.PNG

SIT, Lonavala. Page 81


Computer Network & Security Lab [CNSL] Computer Engineering Department

Click File2 link to view the contents of the file in the browser.

CONCLUSION:

Hence we have studied performance of HTTP, HTTPS and FTP protocol using Packet tracer tool.

SIT, Lonavala. Page 82


Computer Network & Security Lab [CNSL] Computer Engineering Department

Experiment No 13

AIM: Installing and configure DHCP server and write a program to install the software on remote
machine.

OBJECTIVES:
• To study UDP socket programming.
• To implement Peer to Peer chat & Multiuser chat

PROBLEM STATMENT: Installing and configure DHCP server and write a program to install
the software on remote machine.

OUTCOMES:

CO4: Develop Client-Server architectures and prototypes by the means of correct standards and
technology.

SOFTWARE & HARDWARE REQUIREMENTS:

• Software: gcc compiler, jdk.

Hardware: Open source Linux operating system, Ubuntu 14.04 LTS

Theory:
The Dynamic Host Configuration Protocol (DHCP) is a standardized network protocol used on
Internet Protocol (IP) networks for dynamically distributing network configuration parameters,
such as IP addresses for interfaces and services. With DHCP, computers request IP addresses and
networking parameters automatically from a DHCP server, reducing the need for a network
administrator or a user to configure these settings manually. RFC 2131.

The Dynamic Host Configuration Protocol (DHCP) is a network service that enables host
computers to be automatically assigned settings from a server as opposed to manually configuring
each network host. Computers configured to be DHCP clients have no control over the settings
they receive from the DHCP server, and the configuration is transparent to the computer's user.

The most common settings provided by a DHCP server to DHCP clients include:

1. IP address and netmask


2. IP address of the default-gateway to use
3. IP adresses of the DNS servers to use

SIT, Lonavala. Page 83


Computer Network & Security Lab [CNSL] Computer Engineering Department

However, a DHCP server can also supply configuration properties such as:

1. Host Name
2. Domain Name
3. Time Server
4. Print Server

The advantage of using DHCP is that changes to the network, for example a change in the address
of the DNS server, need only be changed at the DHCP server, and all network hosts will be
reconfigured the next time their DHCP clients poll the DHCP server. As an added advantage, it is
also easier to integrate new computers into the network, as there is no need to check for the
availability of an IP address. Conflicts in IP address allocation are also reduced.

A DHCP server can provide configuration settings using the following methods:

Manual allocation (MAC address)


This method entails using DHCP to identify the unique hardware address of each network card
connected to the network and then continually supplying a constant configuration each time the
DHCP client makes a request to the DHCP server using that network device. This ensures that a
particular address is assigned automatically to that network card, based on it's MAC address.

Dynamic allocation (address pool)


In this method, the DHCP server will assign an IP address from a pool of addresses (sometimes
also called a range or scope) for a period of time or lease, that is configured on the server or until
the client informs the server that it doesn't need the address anymore. This way, the clients will be
receiving their configuration properties dynamically and on a "first come, first served" basis. When
a DHCP client is no longer on the network for a specified period, the configuration is expired and
released back to the address pool for use by other DHCP Clients. This way, an address can be
leased or used for a period of time. After this period, the client has to renegociate the lease with
the server to maintain use of the address.

Automatic allocation
Using this method, the DHCP automatically assigns an IP address permanently to a device,
selecting it from a pool of available addresses. Usually DHCP is used to assign a temporary address
to a client, but a DHCP server can allow an infinite lease time.

The last two methods can be considered "automatic" because in each case the DHCP server assigns
an address with no extra intervention needed. The only difference between them is in how long the
IP address is leased, in other words whether a client's address varies over time. Ubuntu is shipped
with both DHCP server and client. The server is dhcpd (dynamic host configuration protocol
daemon). The client provided with Ubuntu is dhclient and should be installed on all computers

SIT, Lonavala. Page 84


Computer Network & Security Lab [CNSL] Computer Engineering Department

required to be automatically configured. Both programs are easy to install and configure and will
be automatically started at system boot.

Installation
At a terminal prompt, enter the following command to install dhcpd:

sudo apt-get install isc-dhcp-server

We need to change the default configuration by editing /etc/dhcp/dhcpd.conf to suit our needs
and particular configuration.

We also may need to edit /etc/default/isc-dhcp-server to specify the interfaces dhcpd should listen
to.

Note: dhcpd's messages are being sent to syslog. Look there for diagnostics messages.

Configuration
The error message the installation ends with might be a little confusing, but the following steps
will help you configure the service:

Most commonly, what you want to do is assign an IP address randomly. This can be done with
settings as follows:

# minimal sample /etc/dhcp/dhcpd.conf


default-lease-time 600; max-lease-time
7200; subnet 192.168.1.0 netmask
255.255.255.0 { range 192.168.1.150
192.168.1.200; option routers
192.168.1.254;
option domain-name-servers 192.168.1.1, 192.168.1.2; option
domain-name "srttc";
}

This will result in the DHCP server giving clients an IP address from the range
192.168.1.150192.168.1.200. It will lease an IP address for 600 seconds if the client doesn't ask
for a specific time frame. Otherwise the maximum (allowed) lease will be 7200 seconds. The server
will also "advise" the client to use 192.168.1.254 as the default-gateway and 192.168.1.1 and
192.168.1.2 as its DNS servers.

CONCLUSION: Hence, we have implemented DHCP installation .

SIT, Lonavala. Page 85


Computer Network & Security Lab [CNSL] Computer Engineering Department

Experiment No.14

AIM: To Study IPsec (ESP and AH) protocol by capturing packets using
Wireshark tool.
OBJECTIVES:
To study IPsec protocol.

PROBLEM STATMENT:
To Study IPsec (ESP and AH) protocol by capturing packets using
Wireshark tool.

OUTCOMES:
CO1:Studied IPsec protocol by wireshark tool.

SOFTWARE & HARDWARE REQUIREMENTS:

Software: Open source O.S.and wireshark, Cisco packet tracer


tool

Theory:
What is IPSEC?

IPSEC, short for IP Security, is a suite of protocols, standards, and


algorithms to secure traffic over an untrusted network, such as the Internet.
IPSEC is supported on both Cisco IOS devices and PIX Firewalls.

IPSEC provides three core services:


Confidentiality – prevents the theft of data, using encryption.

Integrity – ensures that data is not tampered or altered, using a
hashing algorithm.

SIT,Lonavala 86
Computer Network & Security Lab [CNSL] Computer Engineering Department

Authentication – confirms the identity of the host sending data, using pre-
shared keys or a Certificate Authority (CA).


Anti-replay – prevents duplication of encrypted packets, by assigning
a unique sequencing number.

The IPSEC standard is outlined in RFC 2401.

Confidentiality and Encryption

Data sent in clear-text across the Internet can easily be intercepted and
stolen. Because of this, sensitive data should be encrypted when sent across
an untrusted network or domain.

Keys are generated values used to both encrypt and decrypt data. The longer
the key, the more secure that key is. The length of a key is measured in bits.
Two “types” of keys exist:

Symmetric keys can be used to both encrypt and decrypt data. More
specifically, the same key is used to both encrypt a packet (at the sending
device) and then decrypt that packet (at the receiving device). Symmetric
key encryption is efficient, but does not scale well in large environments.

Symmetric keys are not openly shared during data transmit, and must instead
be installed on each machine prior to the transfer of data. This can be
accomplished using a variety of (inefficient and insecure) methods: email,
sneaker-net, and even snail-mail. Each device on a network would require
every other device’s symmetric key, and thus the lack of scalability.

Asymmetric keys require a separate key for encryption (the public key) and
decryption (the private key). Public keys are openly exchanged between
devices to encrypt data during transfer. Private keys are never exchanged.

SIT,Lonavala 87
Computer Network & Security Lab [CNSL] Computer Engineering Department

Consider the above diagram. Assume we are using a public/private key


infrastructure:

Both Router A and Router B have their own unique private key.

Both Router A and Router B exchange unique public keys.

When Router B encrypts data destined for Router A, it uses Router
A’s public key. (and vice versa)

Router A decrypts the data using its private key.

Only the private keys can decrypt the data. Thus, even if the data and the
public key were intercepted, confidentiality is ensured.
Confidentiality and Encryption (continued)

Diffie-Hellman (D-H) Public Key Exchange is the most common standard


used to create and exchange keys across insecure mediums. D-H is not used
to encrypt data, but rather to generate the keys that are used to encrypt and
decrypt data.

A variety of popular standards and protocols utilize D-H key exchange,


including SSL (Secure Socket Layer), SSH (Secure Shell), and IPSEC.

The generated public keys encrypt data payload using one of several
available encryption algorithms:


DES (Data Encryption Standard) – 56-bit key

SIT,Lonavala 88
Computer Network & Security Lab [CNSL] Computer Engineering Department


3DES (Triple Data Encryption Standard) – 168-bit key

AES (Advanced Encryption Standard) - 128, 192, or 256-bit key

Blowfish – up to a 448-bit key

Additionally, the strength of a key is determined by the D-H group used to


generate that key. There are several D-H groups:


Group 1 – 768 bits
• •
Group 2 – 1024 bits Group 5 – 2048 bits Data Integrity and
Hashing

Data sent across the Internet can not only be stolen, but can also be
maliciously altered.

To combat this, a hashing algorithm computes and appends a specific hash


value as each packet is sent. Once the data is received, it is run through the
hashing algorithm again. If the hash value is different, the packet was altered
in transit.

Hashed Message Authentication Code (HMAC) is used to perform this


hashing function. HMAC utilizes a secret key when computing the hash
value, thus preventing an attacker from altering the packet and then
recomputing the correct hash.

Two HMAC algorithms are commonly used:


HMAC-MD5 (Message-Digest 5) – 128-bit hashed key

HMAC-SHA1 (Secure Hash Algorithm) – 160-bit hashed key

SIT,Lonavala 89
Computer Network & Security Lab [CNSL] Computer Engineering Department

Authentication

Another concern when sending data across the Internet is the source or
origin of that data. It is possible to masquerade or spoof one’s identity or
address.

For an IPSEC VPN tunnel to be established, both sides of the tunnel must be
authenticated. To accomplish this, either pre-shared keys or RSA digital
signatures are used.

When using pre-shared keys, a secret string of text is used on each device
to authenticate each other. This string must be pre-agreed upon and identical
on each device. This string is then hashed into a digital signature.

When using RSA Digital signatures, a Certificate Authority (CA) is used


to apply a verified digital signature.

One of the above options must be correctly configured before the VPN
tunnel will become active.

The IPSEC Protocols

IPSEC uses one of two protocol headers for securing data:



Authentication Header (AH)

Encapsulation Security Payload (ESP)

Authentication Header (AH), or IP protocol 51, provides no


confidentiality of data. It does not encrypt any data at all. However, AH
provides both authentication and integrity services. Because AH does not
perform encryption, it is a quicker standard than ESP.

SIT,Lonavala 90
Computer Network & Security Lab [CNSL] Computer Engineering Department

AH uses a hash algorithm to compute a hash value on both the payload and
header of a packet, ensuring integrity of the packet. However, this causes a
very specific problem. AH will not work through a NATed device.

NAT changes the IP header of a packet during translation, but the hash value
is not changed. Thus, the receiving device will believe the packet has been
altered in transit, and reject the packet.

Encapsulation Security Payload (ESP), or IP protocol 50, performs


confidentiality, authentication, and integrity services. Thus, ESP does
perform encryption, and is inherently more secure than AH. ESP introduces
both an additional header and trailer to a packet.

ESP also uses a hash algorithm for data integrity. However, the hash does
not include the IP header of the packet, and thus ESP will (usually) work
through a NATed device.

ESP and AH can be used separately, or used in conjunction with each other.

Transport vs. Tunnel Modes

Each IPSEC protocol (AH or ESP) can operate in one of two modes:


Transport mode – Original IP headers are left intact. Used when
securing communication from one device to another single device.


Tunnel mode – the entire original packet is hashed and/or encrypted,
including both the payload and any original headers. A temporary IP
header is applied to the packet during transit. Used to tunnel traffic from
one site to another.

The following demonstrates how AH alters an IP packet:

SIT,Lonavala 91
Computer Network & Security Lab [CNSL] Computer Engineering Department

Unaltered Packet IP Header TCP Header Data Payload

IP Header AH Header TCP Header Data Payload


AH Transport Mode

Hashed

New IP Header AH Header IP Header TCP Header Data Payload


AH Tunnel Mode
Hashed

The following demonstrates how ESP alters an IP packet:

Unaltered Packet IP Header TCP Header Data Payload

IP Header ESP Header TCP Header Data Payload ESP Trailer


ESP Transport Mode
Encrypted
Hashed

New IP Header ESP Header IP Header TCP Header Data Payload ESP Trailer

ESP Tunnel Mode Encrypted


Hashed

ESP in Tunnel mode experiences NAT difficulties similar to AH. This can
be alleviated by implementing NAT Traversal (NAT-T).

SIT,Lonavala 92
Computer Network & Security Lab [CNSL] Computer Engineering Department

IKE and IPSEC Security Associations

IPSEC VPN peers establish a Security Association (SA), a “connection” or


“policy” between the two endpoints of the VPN tunnel. An SA is a one-way
virtual tunnel between the VPN peers. Thus, for full communication to
occur, two SA’s must be established, one for each direction.

Before the SA can be established, several parameters must be negotiated


between VPN peers, and keys must be both created and exchanged. The
Internet Key Exchange (IKE) protocol controls this negotiation process,
on UDP port 500.

IKE Policy Sets are created to negotiate several parameters, including:



The encryption algorithm (such as DES, 3DES, or AES)

The hashing algorithm (such as MD5 or SHA-1)

The authentication method (such as shared keys or RSA signatures)

The Diffie-Hellman (D-H) group for creating and sharing keys

The SA Lifetime, measured in seconds or in kilobytes sent

IKE policies are often referred to as Internet Security Association and Key
Management Protocol (ISAKMP) policies. Multiple IKE policies can be
created on a VPN peer. During the negotiation process, VPN peers share
their list of configured IKE policies. The SA will only be established if there
is an exact matching policy between the peers.

There are two phases to this negotiation process:

IKE Phase 1 establishes the initial tunnel (referred to as the IKE or


ISAKMP SA). Peers are authenticated, encryption and hashing algorithms
are negotiated, and keys are exchanged based on the IKE Policy Sets. Two
modes can be used for Phase 1 negotiation:

SIT,Lonavala 93
Computer Network & Security Lab [CNSL] Computer Engineering Department


Main Mode – slower, but more secure

Aggressive Mode – faster, but less secure

IKE Phase 2 establishes the IPSEC tunnel (IPSEC SA), which details the
AH or ESP parameters for securing data. These parameters are contained in
an IPSEC Transform Set.

IKE Phase 1 negotiates parameters for the tunnel (key exchange) itself,
while IKE Phase 2 negotiates parameters for the data traversing that tunnel.

The Five Steps of IPSEC

The operation of IPSEC can be described in five steps:

1. Any traffic that should be secured and sent across the tunnel is
identified as interesting traffic, usually using an access-list.

2. IKE (Internet Key Exchange) Phase 1 is initiated. Peers are


authenticated, keys are exchanged, and IKE Policy Sets are
negotiated. If successful, the IKE SA is established.

3. IKE (Internet Key Exchange) Phase 2 is initiated. IPSEC Transform


Sets are negotiated, and if successful, the IPSEC SA is established.

4. Data is actually transferred, using the agreed upon security policy.

5. The session is torn down once the SA Lifetime expires.

CONCLUSION:-Hence, we have Studied IPsec protocol using wireshark.

SIT,Lonavala 94

You might also like