Sunteți pe pagina 1din 58

Mahatma Education Societys

Pillai HOC College of Engineering and Technology, Rasayani


Department of Computer Engineering
OSAY 2014

Lab Manual
Computer Networks
Sem-V

Submitted To: Prof. Sushila Ratre

Submitted By: Student Name

Subject Incharge

Class: TE COMP Div 'C'

Experiment List

Serial

Name of Experiment

No.
1.

Study of LAN Topology

2.

Study of various Network devices

3.

Configure a Network topology using


packet tracer Software

4.

Installation & Configuration of NS2 in


Linux Environment.

5.

Basic wired & Wireless topology in


NS2

6.

Build class A & Class B Network using


router in Packet Tracer tools

7.

Configure a Network using Distance


Vector Routing protocol

8.

A client-server application using socket


programming in Java

9.

How to find IP address of local host


from Java program

10.

Stop and Wait protocol using in socket


program

Date of
Date of
Performance Submission

Sign

Experiment No. 01
Study of LAN Topology
Aim: Study of LAN Topology.
Theory:
Topology is a pattern of network devices and describes the way in which these
devices are connected. Topologies can be physical or logical. Physical topology refers
to the actual physical structure of the network, while a logical topology determines
the way in which the data actually passes through the network from one device to
other. Different types of topologies are:

Bus Topology
Star Topology
Ring Topology
Mesh Topology
Tree Topology
Hybrid Topology

Bus Topology
In a bus topology, devices share a common backbone cable to send and receive
data. A thick co-axial cable is used to connect all devices. Bus topology uses daisy
chain scheme to add more devices in a network. In a daisy chain scheme, device 1
is connected to device 2; device 2 is connected to device 3. The first and last
devices are connected to terminator.

Star Topology

In star topology, multiple devices are connected to a central connection point


known as hub or switch. Devices are attached to the switch by using either copper
cables or fiber optics cable. Start networks provide a cost-effective method for
sharing information between different users. Star topology can be in airline
reservation counters and small business offices where employees want an access
to common application and files.

Ring Topology
In ring topology, each device is connected to adjacent devices forming a circle.
Data flows in only one direction, clockwise or anti-clock wise. Each device in the
ring topology acts as a repeater. It amplifies the signal and transmits it to the next
device.

Mesh Topology

In mesh topology each device is connected to every other device. A device can
send data to all the devices in the network. Data send by the other device can take
any possible path to reach the destination.

Tree topology
A tree topology combines the characteristics of linear bus and star topology. In
tree topology, group of star network are connected to the linear bus backbone.
Tree topology enables the user to expand and configure the existing network
depending on the requirement. Twisted pair of cable is commonly used by tree
topology. Tree topology is also called as hierarchical structure.

Hybrid Topology
Hybrid topology is a combination of different network topologies. It is also known

as a Special Topology. This topology is useful for corporate offices to link their
internal LANs together while adding external networks through Wide Area
Networks (WANs).

Conclusion:
Thus we have studied and understand the different Local Area Network (LAN)
Topologies

Experiment No. 02

Study of various Network devices


Aim: Study of various Networking Devices.
Theory:
Local area networks (LANs) are most commonly used by the organizations.
The organizations need to connect multiple LANs together to extend networks. The
networking devices are also called as internetworking devices which acts as an
intermediate agent for transmission of data in the network. The networking devices
include Hub, Switches, Routers and Gateways. These devices interconnect the
systems linked into large, spread-out group of LANs. The networking devices
manage networks by dividing a single network into multiple sub-networks. This
reduces the number of nodes on a network and so network traffic is also reduced. The
networking devices also provide security by restricting individuals to specified
resources and increases system reliability.
Repeater: Functioning at Physical Layer. A Repeater is an electronic device that
receives a signal and retransmits it at a higher level and/or higher power, or onto the
other side of an obstruction, so that the signals can cover longer distances. Repeaters
have two ports, so cannot be used to connect for more than two devices.

Hub: An Ethernet hub, active hub, network hub, repeater hub, hub or connecter is a
device for connecting multiple twisted pair or fiber optics. A hub is a repeater with
multiple ports simply receives the data from one port and sends the data to all the
ports. Hub allows multiple devices to be connected from single network segment.
Hub operates at the physical layer (layer 1) of the OSI model. Repeater hub also
participates in collision detection, forwarding a jam signal to all ports if it detected a
collision. It is the simplest networking device hence has low cost.

Switch: Now a days switches are mostly used in LAN due to their superior
throughput performance higher post density, lower per-port cost and greater
flexibility. The cost of switch depend on the number of ports. As the number of port
increases, cots increases. Switch is available in 8, 16, 24 and 48 ports. A switch is a
networking device which filters and forwards packets through the network. It is a

layer of 2 devices. It is more advance than a hub but not as advanced as a router.
Switch connect separate LAN segment. It allows multiple systems to transmit
simultaneously.

Bridge: a network bridges connects network segment at the data link layer (layer 2)
of the OSI model. In Ethemet network, the term bridge formally means a device that
behaves according to the IEEE 802ID stander. A bridge and switch are very much
alike, a switch being a bridge with numerous ports. Switch or layer 2 switch is often
use interchangeably with bridge. Bridge can analyze incoming data packets to
determine if the bridge is able to send the given packet to another segment of the
network.

Router: router is an intelligent network layer (layer 3) device. It connects to or more


network segment which may be near or very far and having different types of cabling.
Hence it can work in LAN and WAN environment. Router has LAN ports which are
used to connect to your LAN or computer and WAN ports which are generally used
to connect to some other connection the links to regular phone line, a more advanced
telephone connection like ISDN, ADSL, or T1, or may be a cable modern. Routers
pass the incoming packets form one LAN to another according to the IP addresses
stored in the incoming packets. Routers come in variety of shapes, sizes and
functions. Little routers (Linksys, D-link make) are used in homes and small
businesses. Midsized routers are used to connect a couple of buildings. The massive
backbone routers are used in big organizations.

Gateway: in a communications network, a network node equipped for interfacing


with another network that used different protocols.
A gateway may contain device such as protocol translators, independence
matching devices, rate convertor, fault isolator, or signal translators as
necessary to provide system interoperability. It also requires the establishment
of mutually acceptable administrative procedures between both network.
A protocol translation/mapping gateway interconnects networks with different
network protocol technologies by performing the required protocol
conversions.
Conclusion: Thus studied and we understand the different types of Networking
Devices.

Experiment No. 03
Configure a Network topology using packet tracer Software
Aim: Configure a Network topology using packet tracer Software.
Apparatus (Software): Cisco Packet tracer Software.
Theory:
Star Topology: In star Topology, multiple devices are connected to a central
connection point known as hub or switch. Devices are attached to the switch by using
either copper cable or fiber optic cable. Star networks provide a cost-effective method
for sharing information between different users. Star topology can be used in airline
reservation counters and small business offices where employees want an access to
common applications and files.
Basic Structure of Star Topology: Each device is connected point-to-point to a
central device which is either a hub or switch. Hub manages and controls all the
functions of the network. It also acts as a multi port repeater for the data flows. Hub
is used to connect segments of LAN and contains multiple ports. Hubs can be passive
or active. Passive hubs are used as a connection point which router all the traffic
towards the devices. It does not amplify or regenerate the signals. They simply take
all of the packets they receive on a single port and broadcast them across all the ports.
Actives hubs contain electronic circuits that regenerate and retransmit the
information. Active have all of the features of passive hubs, with the added feature of
actually watching the data before being sent out. Active hubs take a larger role in
Ethernet communication by implementing a technology called store and forward
where the hubs actually look at the data they are transmitting before sending it. Also
it repairs certain damaged packets. The basic structure of star topology is shown in
figure.

Data passed through the hub before reaching the destination. For example, device A
wants to transmit data to device B. device A first sends data to the hub. If the hub is
passive, it broadcast the data to all the device in star network, except device A. each
device has to read the address specified in data to determine if the data is intended foe
that device. If the address is different, then that data is discarded. If the address

matches then the data is received. If the hub is active, it regenerates the data before it
is broadcasted.
A physical star network that used a central hub operates as per logical bus topology.
The hub broadcast data to all segments that thus uses a bus topology for transmission
of data. On the other hand, a physical star network using a switch functions as per
logical star topology. This is because the switch has a capacity to read the address
mentioned in data and to direct the data to the intended receiver.
Advantages and Disadvantages of star Topology: A star network required more
cable wires, but failure in any cable will affect only that particular device and are not
the entire LAN. Star network is easy to install and configure.
Advantages of star topology are:
Easy to install, configure and manage
Easy to detect faulty device
Easier to expand
Connecting or removing devices does not the affect the network
Switch provides a centralized management
Disadvantages of star topology
Increased devices causes traffic which makes the network slow
Requires more cable length than a linear topology
Hub failure leas to network failure
More expensive
Procedure:
1. Open Cisco Packet Tracer software.
2. Click on New tab from menu bar.
3. Drag and drop Generic Hub and place it in blank window.
4. Drag and drop Generic PC-PT (4 in numbers) and place it in blank window.
5. Click on PC0 a new window will appear, select ip configuration from Desktop
tab.
6. Select Static radio button (if not selected) enter the IP address and subnet mask.
7. Repeat the step 4 and 5 for all remaining PCs in network, for example:
a. PC0: IPaddress-192.168.7.1; Subnet mask-255.255.255.0
b. PC1: IPaddress-192.168.7.2; Subnet mask-255.255.255.0
c. PC2: IPaddress-192.168.7.3; Subnet mask-255.255.255.0
d. PC3: IPaddress-192.168.7.4; Subnet mask-255.255.255.0

8. From the left pane select the packet and place it on any PC-PT as a source and
destination.
9. Change Realtime tab to Simulation tab and click Capture/forward tab in it, till
source get acknowledge from destination.

Conclusion: Thus we build a Star topology using Network tool

Experiment No. 04
Study of TCP/IP command

Aim: To study the TCP/IP commands.


Theory:
The Transmission Control Protocol/Internet Protocol (TCP/IP) suite has become the
industry-standard method of interconnecting hosts, networks, and the Internet. As such, it is
seen as the engine behind the Internet and networks worldwide. Although TCP/IP supports a
host of applications, both standard and nonstandard, these applications could not exist
without the foundation of a set of core protocols.
It is sometimes useful to know the network commands to analyze or configure your
TCP/IP networks Here is the list of commands that can be used in the command prompt:

PING:
PING: Test the network connection with a remote IP address
ping-t [IP or host]
ping-l 1024 [IP or host]
The -t option to ping continuously until Ctrl-C is pressed. If you specify the -t option you
can always get statistics without interrupting pings by pressing Ctrl + Break This command
is also useful to generate network load by specifying the size of the packet with the -l option
and the packet size in bytes.

TRACERT:
TRACERT: Displays all intermediate IP addresses through which a packet passes through,
between the local machine and the specified IP address.
tracert [@IP or host]
tracert -d [@IP or host]
This command is useful if the ping command does return any data, to determine at what
level the connection failed.

IPCONFIG:
IPCONFIG: Displays or refresh the TCP/IP configuration.
ipconfig /all [/release [adapter]] [/renew [adapter]] /flushdns /displaydns /registerdns [-a] [a] [-a]
This command, when executed with no options, displays the current IP address, the subnet
mask and default gateway (network interfaces of the local machine)
/all: Displays all network configuration, including DNS, WINS, DHCP servers, etc ...
/renew [adapter]: Renews DHCP configuration for all adapters or a specific adapter
indicated by the [adapter] parameter.
/release [adapter]: Sends a DHCPRELEASE message to the DHCP server to release
the current DHCP configuration and cancel the IP address configuration for all
adapters or a specific adapter indicated by the [adapter] parameter.

NETSTAT:
NETSTAT: Displays the status of the TCP/IP stack on the local machine.
NETSTAT [-a] [-e] [-n] [-s] [-p proto] [-r] [interval]

-a Displays all connections and listening ports (server-side connections are normally
inhibited).
-e Displays Ethernet statistics. Can be combined with the -s option.
-n Displays addresses and port numbers in numerical form.
-p proto Shows connections for the protocol specified by proto, proto may be TCP or
UDP.
Used with the -s option to display per-protocol statistics, proto may be TCP, UDP or
IP.
-r Displays the contents of the routing table.
-s Displays statistics by protocol. By default, statistics on TCP, UDP and IP are
displayed,
the -p option can be used to specify a subset.
interval: Re-display the selected statistics, pausing after a specific "interval" (in
seconds)
between each display. Press Ctrl + C to stop displaying statistics.
-abnov Displays processes using the internet connection (local IP address, port,
remote IP
adress and the PID of the process that uses the connection as well as its name).

ARP:
Resolving IP addresses to MAC addresses. Displays and modifies the translation
tables of IP addresses to physical addresses used by the ARP address resolution protocol.
ARP -s adr_inet adr_eth [adr_if]
ARP -d adr_inet [adr_if]
ARP -a [adr_inet] [-N adr_if]
-a Displays active ARP entries by interrogating the current data protocol. If adr_inet
is specified, only the physical and IP addresses of the specified computer are
displayed. If more than one network interface uses ARP, entries for each ARP table
are displayed.
-g is the same as -a
adr_inet Specifies an internet address.
-N adr_if Displays ARP entries for the network interface specified by adr_if.
-d Deletes the host specified by adr_inet.
-s Adds the host and associates the adr_inet internet address with the adr_eth physical
address. The physical address is given as 6 hexadecimal bytes separated by hyphens.
The entry is permanent.
adr_eth Specifies a physical address.
adr_if Specifies the internet interface whose address translation table should be
modified.When not specified, the first applicable interface will be used.

Output:

Conclusion: Hence we successfully studied about TCP/IP commands.

Experiment No. 05
Aim: To implement Error Detection by using CRC method.
Theory:
When a codeword is transmitted, one or more number of transmitted bits will
be reversed (0 to 1 or vice versa) due to transmission impairments. Thus error will be
introduced. It is possible for the receiver to detect the error if the received codeword
(corrupted) is not one of valid codeword. Hence to detect error at receiver, the valid
codewords should be separated by a distance of more than 1. Otherwise the incorrect
received codeword will also become some other valid codeword and the error
detection will be impossible. The number of error that can be detected depends on the
distance between any two valid codewords.
Some of the most important error detection methods are as follow:
1. Parity checking
2. Checksum error detection
3. Cyclic Redundancy Code (CRC)
Cyclic Redundancy Check (CRe) error detection mechanism in which a
special number is appended to a block of data in order to detect any changes
introduced during storage (or transmission). The CRe is recalculated on retrieval (or
reception) and compared to the value originally transmitted, which can reveal certain
types of error. For example, a single corrupted bit in the data results in a one-bit
change in the calculated CRC, but multiple corrupt bits may cancel each other out.
A CRC is derived using a more complex algorithm than the simple
CHECKSUM, involving MODULO ARITHMETIC (hence the 'cyclic' name) and
treating each input word as a set of coefficients for a polynomial.
CRC is more powerful than VRC and LRC in detecting errors.
It is not based on binary addition like VRC and LRC. Rather it is based on
binary division.
At the sender side, the data unit to be transmitted IS divided by a
predetermined divisor (binary number) in order to obtain the remainder. This
remainder is called CRC.
The CRC has one bit less than the divisor. It means that if CRC is of n bits,
divisor is of n+ 1 bit.
The sender appends this CRC to the end of data unit such that the resulting
data unit becomes exactly divisible by predetermined divisor i.e. remainder becomes
zero.
At the destination, the incoming data unit i.e. data + CRC is divided by the
same number (predetermined binary divisor).
If the remainder after division is zero then there is no error in the data unit &
receiver accepts it.
If remainder after division is not zero, it indicates that the data unit has been
damaged in transit and therefore it is rejected.
This technique is more powerful than the parity check and checksum error

detection.
CRC is based on binary division. A sequence of redundant bits called CRC or
CRC remainder is appended at the end of a data unit such as byte.
Requirements of CRC :
A CRC will be valid if and only if it satisfies the following requirements:
It should have exactly one less bit than divisor.
Appending the CRC to the end of the data unit should result in the bit sequence
which is exactly divisible by the divisor.
The various steps followed in the CRC method are
A string of n as is appended to the data unit. The length of predetermined
divisor is n+ 1.
The newly formed data unit i.e. original data + string of n as are divided by the
divisor using binary division and remainder is obtained. This remainder is called
CRC.

Now, string of n Os appended to data unit is replaced by the CRC remainder


(which is also of n bit).
The data unit + CRC is then transmitted to receiver.
The receiver on receiving it divides data unit + CRC by the same divisor &
checks the remainder.
If the remainder of division is zero, receiver assumes that there is no error in
data and it accepts it.
If remainder is non-zero then there is an error in data and receiver rejects it.
For example, if data to be transmitted is 1001 and predetermined divisor is
1011. The procedure given below is used:
String of 3 zeroes is appended to 1011 as divisor is of 4 bits. Now newly
formed data is 1011000.

1. Data unit 1011000 is divided by 1011.

During this process of division, whenever the leftmost bit of dividend or


remainder is 0, we use a string of Os of same length as divisor. Thus in this case
divisor 1011 is replaced by 0000.
At the receiver side, data received is 1001110.
This data is again divided by a divisor 1011.
The remainder obtained is 000; it means there is no error.

CRC can detect all the burst errors that affect an odd number of bits.
The probability of error detection and the types of detectable errors depends on
the choice of divisor.
Thus two major requirement of CRC are:
CRC should have exactly one bit less than divisor.
Appending the CRC to the end of the data unit should result in the bit sequence
which is exactly divisible by the divisor.
Polynomial codes
A pattern of Os and 1s can be represented as a polynomial with coefficient of o
and 1.
Here, the power of each term shows the position of the bit and the coefficient
shows the values of the bit.
For example, if binary pattern is 100101, its corresponding polynomial
representation is x5 + x2 + 1. Figure shows the polynomial where all the terms with
zero coefficient are removed and x J is replaced by x and XO by 1.

The benefits of using polynomial codes are that it produces short codes. For
example here a 6-bit pattern is replaced by 3 terms.
In polynomial codes, the degree is 1 less than the number of bits in the binary
pattern. The degree of polynomial is the highest power in polynomial. For example as
shown in fig degree of polynomial x5 +x2 + 1 are 5. The bit pattern in this case is 6.

Addition of two polynomials is based on modulo-2 method. In such as case,


addition and subtraction is same.
Addition or subtraction is .done by combining terms and deleting pairs of
identical terms. For example adding x5 + x4 + x2 and x6 + x4 + x2 give x6 + x5. The
terms x4 and x2 are deleted.
If three polynomials are to be added and if we get a same term three times, a
pair of them is detected and the third term is kept. For example, if there is x2 three
times then we keep only one x2.
In case of multiplication of two polynomials, their powers are added. For
example, multiplying x5 + x3 + x2 + x with x2+ x+ 1 yields:
(X5 + x3 + x2 + x) (x2 + x + 1)
= x7 + x6+ x5+ x5+ x4+ x3+ x4+ x3+ x2+ x3+ x2+ x
=X7+x6+x3+X
In this, first polynomial is multiplied by all terms of second. The result is then
simplified and pairs of equal terms are deleted.
In case of division, the two polynomials are divided as per the rules of binary
division, until the degree of dividend is less than that of divisor.
CRC generator using polynomials
If we consider the data unit 1001 and divisor or polynomial generator 1011their
polynomial representation is:

Now string of n 0s (one less than that of divisor) is appended to data. Now data
is 1001000 and its corresponding polynomial representation is x6 + x3.

The division of x6+x3 by x3+x+ 1 is shown in fig.


The polynomial generator should have following properties:
It should have at least two terms.
The coefficient of the term x0 should be 1.
It should not be divisible by x.
It should be divisible by x+ 1.
Conclusion:
Thus, we studied and implemented the Cyclic Redundancy Check
Method of Error Detection.

Conclu
sion: Thus we implemented error detection mechanism by using CRC method in
java.

Experiment No. 06
Build class A & Class B Network using router in Network tool.
Aim: Build class A & Class B Network using router in Network tool.
Theory:
IP Address
A unique address mostly used by computers to communicate over a network that use
IP as its basic protocol is known as IP address. IP address is a unique number
assigned to any device operating on a network, for example, computer, routers,
printers, internet fax machine. Hence, an IP address is used to identify the devices in
a network.
For example, IP address is 11000000.10101000.001010.00000001 in binary format
but generally we donate in dotted decimal i.e. 192.168.42.1. Each of the decimal
numbers in an IP address is called octet. So, far the IP address 192.168.42.1, the first
octet is 192, the second octet is 168 and so on. The range of decimal number in each
octet varies is form 0 to 255
Generally, we do not assign an IO address to a computer rather we assign it for the
interface i.e. the Network Interface Card (NIC). So, if you have two NICs in your

computer than you have to assign two IP addresses for both NIC;s to communicate to
the same or two different network.

Dotted decimal notation of IP address:


To take the IP address easier to read and interpret, they are written in decimal format
where a point is separated by a byte. As each byte is 8-bit long, each number
specified by dotted decimal notation lies between 0 and 255, for example
Binary
format
Dotted
decimal
format

10000000.

00001011.

00000011.

00011111

128.

11.

3.

31

IP Address Classes (Classful IP Addressing):


IP address is divided into 5 classes:
Class A
Class B
Class C
Class D
Class E
The scheme of IP addressing using address class is called Classful addressing.
Classful addressing allows only network blocks from Class A, Class B and Class
C prefix corresponding to 8-bits, 16-bit network prefix addresses. The addressing
scheme does not allow any other network prefix addresses. TCP/IP defines Class
D for multicasting and Class E for experimental purpose.
IP address contains two addresses; Network address and Host address as shown in
the figure

Class A addressing
Class A consists of 8-bit network ID and 24-bit host ID as shown in figure

So, each network in class A will have 224 -2=16.777.214 number of host (IP)
addresses available to assign to the devices except for to reserved host addresses in
each network. Class A can be divided into 127 network blocks (number of networks)
where the first network block address starts from 0.0.0.0 to 0.255.255.255 where 0
(first bytes) is the network ID. Similarly, second network block address starts from
1.0.0.0 to 1.255.255.255 where 1 (first byte) is the network ID for second block are
reserved from special purpose. Class A provides 1 reserved network address block for
private address.
Hence, Class A provides 125 network blocks while each block in Class A
provides 16.777.216 host addresses that is why it is used to serve IP addresses for big
organizations. Considering a single network block, within host addresses the first host
address and the last host address is reserved for special use.
Class B addressing
Class A consists of 16-bit network ID and 16-bit host ID as shown in figure

So, each network in Class B will have 216 -2=65.534 number of host (IP) addresses
available to assign to the devices. This address class consists of 16.384 network
blocks. The first block starts from 128.0.255.255. in this address class the first two
bytes represent Network ID that is 128.0.x..x where x is any number between 0 and
255. The second network block starts from 129.0.0 to 129.255.255.255. The last
network block of Class B is 191.255.0.0 to 191.255.255.255 where, the network ID
of the last block is 191.255.X.X.
Class B provides 16 reserved network address block for private addresses.
Hence, the remaining 16.368 network address blocks are use for assigning address to

various organizations. Each network address block in this class contains 65.536 host
address. Within host addresses in a network block, the first host address and the last
host address is reserved for special use. Class B designed ti serve IP addresses for
mid level organizations.
Class C addresses
Class C addresses consists of 24 bits network ID and 8 bits host ID shown in figure

So, each network in Class A will have 28 -2=254 number of host (IP) addresses
available to assign to the devices. Class C address class supports 2,097,152 network
blocks. The first network blocks starts from 192.0.0.0 to 192.0.0.255 The last
network block in Class C starts from 223.225.255.0 to 223.255.255.255 where
network ID is 223.255.255.x. The Network ID field is represented by first three
bytes, 192.0.0.x.
Class C provides 256 network blocks which are reserved for private addresses.
The remaining 2.0960896 networks blocks are use. Each block of Class C address
provides 256 host addresses. Within host addresses in each network block the first
host address and the last host address is reserved for special use. Class C is designed
to serve IP address to smaller organizations.
Class D addresses
Class D address class is designed for multicasting. Each address in this defines a
particular group of host over this internet. This class of address consists of only one
block of address. When a group of computers are assigned an address from this class
each host within the group has a multicast address in addition to its normal address.
First byte of class D specifies decimal values from 224 to 239.
Class E addresses
Class E address is reserved for future and experimental use. First byte of class E
specifies decimal values from 240 to 255.
The selection of class is mostly based on the number of hosts required by the
organization as given in table
Address
class

Starting
(first

Start
address

Last address

Networks Host per


exist per network

Class A
Class B
Class C
Class D
Class E

bytes)
0
10
110
1110
1111

0.0.0.0
128.0.0.0
192.0.0.0
224.0.0.0
240.0.0.0

123,255,255,255
191,255,255,255
223,255,255,255
239,255,255,255
255,255,255,255

class
128
16.777.214
16384
65.534
2.097.152 254
Multicast reserved
Reserved for future use

Table: Address Classes


Identifying the Class of IP Address:
The IP address when specified in binary format can be classified into various classes
by identifying the starting bit of first bit of 32-bit IP address as shown in table above.
When the address is specified in dotted decimal the decimal values given by the first
byte decides the class of IP address.
Class First Octet Range
Valid Network Total no. of Number of
Number
this Class of Hosts
per
Network
Network
7
A
1 to 127
1.0.0.0 to
2 -2
224-2
126.0.0.0
B
127 to 191
128.1.0.0 to
214-2
216-2
192.254.0.0
C
192 to 223
192.0.1.0 to
221-2
28-2
223.255.254.0
Table: Number of Hosts in each Class A, B and C Network
Procedure:
1. Select two Router, two Switch and four PCs.
2. Connect the as shown in figure below.

3. Configure two PCs with Class A IP address and remaining two PCs with class
B IP address.

4. Configure Router1 for interface


a. Fast Ethernet (0/0)
Router>enable
Router#configure terminal
Enter configuration commands, one per line. End with CNTL/Z.
Router(config)#interface FastEthernet0/0
Router(config-if)#ip address 10.0.0.1 255.0.0.0
Router(config-if)#no shutdown
%LINK-5-CHANGED: Interface FastEthernet0/0, changed state to up
%LINEPROTO-5-UPDOWN:
Line
FastEthernet0/0, changed state to up

protocol

Router(config-if)#
b. Serial (2/0)
Router(config-if)#exit
Router(config)#interface Serial2/0
Router(config-if)#ip address 192.0.0.1 255.255.255.0
Router(config-if)#no shutdown
Router(config-if)#
5. Configure Router2 for interface

on

Interface

a. Fast Ethernet (0/0)


Router>enable
Router#configure terminal
Enter configuration commands, one per line. End with CNTL/Z.
Router(config)#interface FastEthernet0/0
Router(config-if)#ip address 172.0.0.1 255.255.0.0
Router(config-if)#no shutdown
%LINK-5-CHANGED: Interface FastEthernet0/0, changed state to up
%LINEPROTO-5-UPDOWN:
Line
FastEthernet0/0, changed state to up

protocol

on

Interface

Router(config-if)#
b. Serial (2/0)
Router(config-if)#exit
Router(config)#interface Serial2/0
Router(config-if)#ip address 192.0.0.2 255.255.255.0
Router(config-if)#
%LINK-5-CHANGED: Interface Serial2/0, changed state to up
no shutdown
Router(config-if)#
6. Configure router to Static Route for packet transfer
a. Router1
Router(config-if)#exit
Router(config)#ip route 172.0.0.0 255.255.0.0 192.0.0.2
Router(config)#
b. Router2
Router(config-if)#exit
Router(config)#ip route 10.0.0.0 255.0.0.0 192.0.0.1
Router(config)#
7. Select the simulation tab and also select simple PDU packet and place it on
source and the destination.
8. Click on Capture / forward table from the simulation window to watch transfer
of packet from source to destination.

Conclusion:
Thus, we have studied and Implemented Build class A & Class B Network
using router in Network tool.

Experiment No. 07
Configure a Network using Distance Vector Routing protocol
Aim: Configure a Network using Distance Vector Routing protocol.
Theory:
In this algorithm, each router maintains a table called vector, such a table gives
the best known distance to each destination and the information about which line to
be used to reach there.
This algorithm is sometimes called by other names such as:
Distributed Bellman-Ford routing algorithm.
Ford-Fulkerson algorithm
In distance vector routing, each router maintains a routing table. It contains one entry
for each router in the subnet.
This entry has two parts :
The first part shows the preferred outgoing line to be used to reach the
destination and
Second part gives an estimate of the time or distance to the destination.
The two fundamental routing algorithms in packet switched networks are:
Distance vector routing
Link state routing.
Both these algorithms assume that a router knows the address of each neighbor and
the cost of reaching each neighbor. In the distance routing, a node tells its neighbors
about its distance to every other node in the network. Whereas in the link state
routing, a node tells every other node in the network its distance to its neighbors. So
both these routing algorithms are distributed type and so they are suitable for large
internetworks.
Distance vector:
In distance vector routing, we assume that each router knows the identity of every
other router in the network, but the shortest part to each router is not known. A
distance vector is defined as the list of <destination, cost> tuples, one tuple per
destination. Each router maintains a distance vector. The cost in each tuple is equal
the sum of costs on the shortest path to the destination.
Updating of router tables:
A router periodically sends a copy of its distance vector to all its neighbors. When a
router receives a distance vector from its neighbor, it determines whether its cost to
reach any destination would decrease if it routed packets to that destination through
that neighbor. This is illustrated in Fig. 1

Fig 1
Fig. 1 shows how the D.V. at A is automatically modified when a D.V. arrives from B.
A similar calculation takes place at the other routers as well. In Fig. 5.3(a) the initial
distance vector is shown. The entries correspond to the costs corresponding to the
shortest distance between the routers corresponding to that square. For example, AC
= 3 indicates the cost corresponding to the shortest path in terms of number of hops
from A to C. Even if nodes asynchronously update their distance vectors the routing
tables eventually converge. The well known example of distance vector routing is the
Bellman-Ford algorithm.
Routing procedure in distance vector routing :
The example of a subnet is shown in Fig. 2 and the routing tables are shown in Fig. 3

Fig 2

Fig 3
The entries in router tables of Fig. 2 are the delay vectors. For example consider the
shaded boxes of Fig. 2 The entry in the first shaded box shows that the delay from A
to B is 10 msec, whereas the entry in the other shaded box indicates that the delay
from A to D is 38 msec. Consider how router I computes its new route to router G.
Fig. 4 shows the two possible routes between I and G.

Fig. 4

The best of these values is 18 msec corresponding to the path IHG. Hence it makes an
entry in its routing table (I's table) that the delay to G is 18 msec and that the route to
use it is via H. The new routing table for router I is shown in Fig. 3 Similarly we can
calculate the delays, from I to different destinations from A to I and enter the
minimum possible delay into the I's router table.
Disadvantages:
1. The problem with distance vector routing is its slowness in converging to the
correct answer. This is due to a problem called count-to-infinity problem.
2. This problem can be solved by using the split horizon algorithm.
3. Another problem is that this algorithm does not take the line bandwidth into
consideration when choosing root.
4. This is a serious problem which led to the replacement of this algorithm by the
Link State Routing algorithm.

Procedure:
1. Develop a
Topology
shown in
figure given
below.
2. Configure
all Routers
3. Implement
RIP
protocols in
Router to
configure
Network.
Router0 configuration.....
Continue with configuration dialog? [yes/no]: no
Press RETURN to get started!
Router>
Router>en
Router#config t
Enter configuration commands, one per line. End with CNTL/Z.
Router(config)#hostname router0
router0(config)#int lo0
%LINK5CHANGED: Interface Loopback0, changed state to up
%LINEPROTO5UPDOWN: Line protocol on Interface Loopback0, changed state
to up
router0(configif)#ip address 10.1.1.1 255.255.255.0
router0(configif)#int f0/0
router0(configif)#ip address 10.1.12.1 255.255.255.0
router0(configif)#no shut
%LINK5CHANGED: Interface FastEthernet0/0, changed state to up
router0(configif)#int f0/1
router0(configif)#ip address 10.1.14.1 255.255.255.0
router0(configif)#no shut
%LINK5CHANGED: Interface FastEthernet0/1, changed state to up
router0(configif)#end
%SYS5CONFIG_I: Configured from console by console
router0#wr
Building configuration...
[OK]
router0#
router0#
%LINEPROTO5UPDOWN: Line protocol on Interface FastEthernet0/0, changed
state to up

%LINEPROTO5UPDOWN: Line protocol on Interface FastEthernet0/1, changed


state to up
router0 con0 is now available
Press RETURN to get started.
router0>
router0>en
router0#config t
Enter configuration commands, one per line. End with CNTL/Z.
router0(config)#router rip
router0(configrouter)#net 10.0.0.0
router0(configrouter)#
router0(configrouter)#end
%SYS5CONFIG_I: Configured from console by console
router0#show ip route
Codes: C connected, S static, I IGRP, R RIP, M mobile, B BGP
D EIGRP, EX EIGRP external, O OSPF, IA OSPF inter area
N1 OSPF NSSA external type 1, N2 OSPF NSSA external type 2
E1 OSPF external type 1, E2 OSPF external type 2, E EGP
i ISIS, L1 ISIS level1, L2 ISIS level2, ia ISIS inter area
* candidate default, U peruser static route, o ODR
P periodic downloaded static route
Gateway of last resort is not set
10.0.0.0/24 is subnetted, 3 subnets
C
10.1.1.0 is directly connected, Loopback0
C
10.1.12.0 is directly connected, FastEthernet0/0
C
10.1.14.0 is directly connected, FastEthernet0/1
router0#
router0#
Router1 Configuration.....
Continue with configuration dialog? [yes/no]: no
Press RETURN to get started!
Router>enable
Router#config t
Enter configuration commands, one per line. End with CNTL/Z.
Router(config)#int lo0
%LINK5CHANGED: Interface Loopback0, changed state to up
%LINEPROTO5UPDOWN: Line protocol on Interface Loopback0, changed state
to up
Router(configif)#ip address 10.1.2.1 255.255.255.0
Router(configif)#no shut
Router(configif)#int f0/1
Router(configif)#ip address 10.1.23.1 255.255.255.0
Router(configif)#no shut

%LINK5CHANGED: Interface FastEthernet0/1, changed state to up


Router(configif)#int f0/0
Router(configif)#ip address 10.1.12.2 255.255.255.0
Router(configif)#no shut
%LINK5CHANGED: Interface FastEthernet0/0, changed state to up
%LINEPROTO5UPDOWN: Line protocol on Interface FastEthernet0/0, changed
state to up
Router(configif)#end
%SYS5CONFIG_I: Configured from console by console
Router#wr
Building configuration...
[OK]
Router#
Router#
Router#
%LINEPROTO5UPDOWN: Line protocol on Interface FastEthernet0/1, changed
state to up
Router con0 is now available
Press RETURN to get started.
Router>
Router>en
Router#con t
% Ambiguous command: "con t"
Router#co t
% Ambiguous command: "co t"
Router#conf t
Enter configuration commands, one per line. End with CNTL/Z.
Router(config)#router rip
Router(configrouter)#net 10.0.0.0
Router(configrouter)#
Router(configrouter)#
Router(configrouter)#end
%SYS5CONFIG_I: Configured from console by console
Router#
Router2 Configuration.....
Continue with configuration dialog? [yes/no]: no
Press RETURN to get started!
Router>en
Router#config t
Enter configuration commands, one per line. End with CNTL/Z.
Router(config)#int lo0
%LINK5CHANGED: Interface Loopback0, changed state to up
%LINEPROTO5UPDOWN: Line protocol on Interface Loopback0, changed state
to up

Router(configif)#ip address 10.1.3.1 255.255.255.0


Router(configif)#no shut
Router(configif)#int f0/0
Router(configif)#ip address 10.1.23.2 255.255.255.0
Router(configif)#no shut
%LINK5CHANGED: Interface FastEthernet0/0, changed state to up
%LINEPROTO5UPDOWN: Line protocol on Interface FastEthernet0/0, changed
state to up
Router(configif)#int f0/1
Router(configif)#ip address 10.1.34.1 255.255.255.0
Router(configif)#no shut
%LINK5CHANGED: Interface FastEthernet0/1, changed state to up
outer(configif)#End
%SYS5CONFIG_I: Configured from console by console
Router#wr
Building configuration...
[OK]
Router#
Router#
Router#
%LINEPROTO5UPDOWN: Line protocol on Interface FastEthernet0/1, changed
state to up
Router con0 is now available
Press RETURN to get started.
Router>
Router>
Router>en
Router#show ip route
Codes: C connected, S static, I IGRP, R RIP, M mobile, B BGP
D EIGRP, EX EIGRP external, O OSPF, IA OSPF inter area
N1 OSPF NSSA external type 1, N2 OSPF NSSA external type 2
E1 OSPF external type 1, E2 OSPF external type 2, E EGP
i ISIS, L1 ISIS level1, L2 ISIS level2, ia ISIS inter area
* candidate default, U peruser static route, o ODR
P periodic downloaded static route
Gateway of last resort is not set
10.0.0.0/24 is subnetted, 3 subnets
C
10.1.3.0 is directly connected, Loopback0
C
10.1.23.0 is directly connected, FastEthernet0/0
C
10.1.34.0 is directly connected, FastEthernet0/1
Router#config t
Enter configuration commands, one per line. End with CNTL/Z.
Router(config)#router rip
Router(configrouter)#net 10.0.0.0

Router(configrouter)#end
%SYS5CONFIG_I: Configured from console by console
Router#
Router#
Router#show ip route
Codes: C connected, S static, I IGRP, R RIP, M mobile, B BGP
D EIGRP, EX EIGRP external, O OSPF, IA OSPF inter area
N1 OSPF NSSA external type 1, N2 OSPF NSSA external type 2
E1 OSPF external type 1, E2 OSPF external type 2, E EGP
i ISIS, L1 ISIS level1, L2 ISIS level2, ia ISIS inter area
* candidate default, U peruser static route, o ODR
P periodic downloaded static route
Gateway of last resort is not set
10.0.0.0/24 is subnetted, 7 subnets
R
10.1.1.0 [120/2] via 10.1.23.1, 00:00:19, FastEthernet0/0
R
10.1.2.0 [120/1] via 10.1.23.1, 00:00:19, FastEthernet0/0
C
10.1.3.0 is directly connected, Loopback0
R
10.1.12.0 [120/1] via 10.1.23.1, 00:00:19, FastEthernet0/0
R
10.1.14.0 [120/2] via 10.1.23.1, 00:00:19, FastEthernet0/0
C
10.1.23.0 is directly connected, FastEthernet0/0
C
10.1.34.0 is directly connected, FastEthernet0/1
Router#
Router#
Router#
Router3 Configuration.......
Continue with configuration dialog? [yes/no]: no
Press RETURN to get started!
Router>
Router>en
Router#config t
Enter configuration commands, one per line. End with CNTL/Z.
Router(config)#int lo0
%LINK5CHANGED: Interface Loopback0, changed state to up
%LINEPROTO5UPDOWN: Line protocol on Interface Loopback0, changed state
to up
Router(configif)#int f0/0
Router(configif)#ip address 10.1.34.2 255.255.255.0
Router(configif)#no shut
%LINK5CHANGED: Interface FastEthernet0/0, changed state to up
%LINEPROTO5UPDOWN: Line protocol on Interface FastEthernet0/0, changed
state to up
Router(configif)#
Router(configif)#int f0/1
Router(configif)#ip address 10.1.14.2 255.255.255.0

Router(configif)#no shut
%LINK5CHANGED: Interface FastEthernet0/1, changed state to up
%LINEPROTO5UPDOWN: Line protocol on Interface FastEthernet0/1, changed
state to up
Router(configif)#end
%SYS5CONFIG_I: Configured from console by console
Router#wr
Building configuration...
[OK]
Router#
Router#
Router#show ip route
Codes: C connected, S static, I IGRP, R RIP, M mobile, B BGP
D EIGRP, EX EIGRP external, O OSPF, IA OSPF inter area
N1 OSPF NSSA external type 1, N2 OSPF NSSA external type 2
E1 OSPF external type 1, E2 OSPF external type 2, E EGP
i ISIS, L1 ISIS level1, L2 ISIS level2, ia ISIS inter area
* candidate default, U peruser static route, o ODR
P periodic downloaded static route
Gateway of last resort is not set
10.0.0.0/24 is subnetted, 2 subnets
C
10.1.14.0 is directly connected, FastEthernet0/1
C
10.1.34.0 is directly connected, FastEthernet0/0
Router#conf t
Enter configuration commands, one per line. End with CNTL/Z.
Router(config)#router rip
Router(configrouter)#net 10.0.0.0
Router(configrouter)#
Router(configrouter)#end
%SYS5CONFIG_I: Configured from console by console
Router#show ip route
Codes: C connected, S static, I IGRP, R RIP, M mobile, B BGP
D EIGRP, EX EIGRP external, O OSPF, IA OSPF inter area
N1 OSPF NSSA external type 1, N2 OSPF NSSA external type 2
E1 OSPF external type 1, E2 OSPF external type 2, E EGP
i ISIS, L1 ISIS level1, L2 ISIS level2, ia ISIS inter area
* candidate default, U peruser static route, o ODR
P periodic downloaded static route
Gateway of last resort is not set
10.0.0.0/24 is subnetted, 7 subnets
R
10.1.1.0 [120/1] via 10.1.14.1, 00:00:09, FastEthernet0/1
R
10.1.2.0 [120/2] via 10.1.34.1, 00:00:14, FastEthernet0/0
[120/2] via 10.1.14.1, 00:00:09, FastEthernet0/1
R
10.1.3.0 [120/1] via 10.1.34.1, 00:00:14, FastEthernet0/0

R
10.1.12.0 [120/1] via 10.1.14.1, 00:00:09, FastEthernet0/1
C
10.1.14.0 is directly connected, FastEthernet0/1
R
10.1.23.0 [120/1] via 10.1.34.1, 00:00:14, FastEthernet0/0
C
10.1.34.0 is directly connected, FastEthernet0/0
Router#
Conclusion: Thus, we configure a Network using Distance Vector Routing protocol.

Experiment No. 08
A client-server application using socket programming in Java
Aim: A client-server application using socket programming in Java
Theory:
Client-Server Model
The clientserver model of computing is a distributed application that partitions tasks
or workloads between the providers of a resource or service, called servers, and
service requesters, called clients. Often clients and servers communicate over a
computer network on separate hardware, but both client and server may reside in the
same system. A server machine is a host that is running one or more server programs
which share their resources with clients. A client does not share any of its resources,
but requests a servers content or service function. Clients therefore initiate
communication sessions with servers which await incoming requests
Socket Programming
A socket is one of the most fundamental technologies of computer networking.
Sockets allow applications to communicate using standard mechanisms built into
network hardware and operating systems.
A socket represents a single connection between exactly two pieces of software. More
than two pieces of software can communicate in client/server or distributed systems
(for example, many Web browsers can simultaneously communicate with a single
Web server) but multiple sockets are required to do this. Sockets are bidirectional,
meaning that either side of the connection is capable of both sending and receiving
data. Libraries implementing sockets for Internet Protocol use TCP for streams, UDP
for datagrams, and IP itself for raw sockets.

Writing a Server
In this post, the server is simply going to respond to a newly connected client with the
following string. Hello. You are connected to a Simple Socket Server. What is your
name?. As mentioned earlier, we will gradually increase the capability of the server
in subsequent parts of the series. Lets look at the code.
package pk.edu.ucp.web.socketServer;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
/**
* A simple socket server
* @author faheem
*
*/
public class SocketServer {
private ServerSocket serverSocket;
private int port;
public SocketServer(int port) {
this.port = port;
}
public void start() throws IOException {
System.out.println("Starting the socket server at port:" + port);
serverSocket = new ServerSocket(port);
//Listen for clients. Block till one connects
System.out.println("Waiting for clients...");
Socket client = serverSocket.accept();
//A client has connected to this server. Send welcome message
sendWelcomeMessage(client);
}
private void sendWelcomeMessage(Socket client) throws IOException {
BufferedWriter writer = new BufferedWriter(new
OutputStreamWriter(client.getOutputStream()));

writer.write("Hello. You are connected to a Simple Socket Server. What is your


name?");
writer.flush();
}
/**
* Creates a SocketServer object and starts the server.
*
* @param args
*/
public static void main(String[] args) {
// Setting a default port number.
int portNumber = 9990;
try {Procedure: To implement this practical following network topology is
required to be
configured using the commands learned in previous practical.
After configuring the given network a packet should be ping from any one machine
to
another.
// initializing the Socket Server
SocketServer socketServer = new SocketServer(portNumber);
socketServer.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Writing a Client
This client will connect to the server that we have created, and as soon as the
connection is created, it will ask the server for any information it needs to send to the
client. The client will then write that information to the console.
package pk.edu.ucp.web.socketClient;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;

/**
* A Simple Socket client that connects to our socket server
* @author faheem
*
*/
public class SocketClient {
private String hostname;
private int port;
Socket socketClient;
public SocketClient(String hostname, int port){
this.hostname = hostname;
this.port = port;
}
public void connect() throws UnknownHostException, IOException{
System.out.println("Attempting to connect to "+hostname+":"+port);
socketClient = new Socket(hostname,port);
System.out.println("Connection Established");
}
public void readResponse() throws IOException{
String userInput;
BufferedReader stdIn = new BufferedReader(new
InputStreamReader(socketClient.getInputStream()));
System.out.println("Response from server:");
while ((userInput = stdIn.readLine()) != null) {
System.out.println(userInput);
}
}
public static void main(String arg[]){
//Creating a SocketClient object
SocketClient client = new SocketClient ("localhost",9990);
try {
//trying to establish connection to the server
client.connect();
//if successful, read response from server
client.readResponse();
} catch (UnknownHostException e) {
System.err.println("Host unknown. Cannot establish connection");
} catch (IOException e) {
System.err.println("Cannot establish connection. Server may not be
up."+e.getMessage());

}
}
}

Conclusion: Thus we implemented client-server application using socket


programming in Java.

Experiment No. 09
How to find IP address of local host from Java program
Aim: How to find IP address of local host from Java program
Theory:
Java networking API provides method to find IP address of localhost from Java
program by using java.net. InetAddress class. Its rare when you need IP address for
localhost in Java program. Mostly I used Unix command to find IP address of
localhost. For all practical purpose where program doesnt need IP address but you
need to troubleshoot any networking issues, Use DOS or windows command or Use
Linux commands. Recently one of my friend faced this question in a core Java
interview, where they are expecting Java developer with some socket programming
experience, But until you know or you have done it before its hard to answer this fact
based question, which motivates me to write this post. In this Java tutorial we will see
How to find IP address of localhost from Java program. By the way its also good to
remember list of Unix networking commands to troubleshoot any networking issues
related to Java application in Unix environment.
InetAddress from java.net package is used to represent an IP address in Java. an IP
address is a 32 or 128 bit unsigned number used by IP protocol which is backbone of
many popular protocols like TCP and UDP. There are two kinds of IP address IPv4
and IPv6 and IP address is associated with host which can be find by host name
resolution process. Hostname resolution is performed by combining local machine
configuration and network naming services such as the DNS(Domain name system)
and NIS(Network Information Service). InetAddress has method to resolve hostname
and IP address and vice versa. Here is a complete code example of finding IP address
from Java program.
Program :
import java.net.InetAddress;
public class Main {
public static void main(String[] args)
throws Exception {
InetAddress addr = InetAddress.getLocalHost();
System.out.println("Local HostAddress:
"+addr.getHostAddress());
String hostname = addr.getHostName();
System.out.println("Local host name: "+hostname);
}
}

OUTPUT:
Local HostAddress: 192.168.1.4
Local host name: yogesh
Conclusion: Thus we implemented a program in Java for finding IP address of local
host.

Experiment No. 10
Stop & wait protocol using sockets in java
Aim: Stop & wait protocol using sockets in java
Theory:
Error Control
When data-frame is transmitted there are probabilities that data-frame may be lost in
the transit or it is received corrupted. In both scenarios, the receiver does not receive
the correct data-frame and sender does not know anything about any loss. In these
types of cases, both sender and receiver are equipped with some protocols which
helps them to detect transit errors like data-frame lost. So, either the sender
retransmits the data-frame or the receiver may request to repeat the previous dataframe.
Requirements for error control mechanism:

Error detection: The sender and receiver, either both or any, must ascertain
that theres been some error on transit.

Positive ACK: When the receiver receives a correct frame, it should


acknowledge it.

Negative ACK: When the receiver receives a damaged frame or a duplicate


frame, it sends a NACK back to the sender and the sender must retransmit the correct
frame.

Retransmission: The sender maintains a clock and sets a timeout period. If an


acknowledgement of a data-frame previously transmitted does not arrive in the
timeout period, the sender retransmit the frame, thinking that the frame or its
acknowledge is lost in transit.
There are three types of techniques available which Data-link layer may deploy to
control the errors by Automatic Repeat Requests (ARQ):

STOP-AND-WAIT ARQ

The following transition may occur in Stop-and-Wait ARQ:


o
The sender maintains a timeout counter. When a frame is sent the sender
starts the timeout counter. If acknowledgement of frame comes in time, the sender
transmits the next frame in queue. If acknowledgement does not come in time, the
sender assumes that either the frame or its acknowledgement is lost in transit. Sender
retransmits the frame and starts the timeout counter. If a negative acknowledgement
is received, the sender retransmits the frame.
//SENDER PROGRAM
import java.io.*;
import java.net.*;
public class Sender
{
Socket sender;
ObjectOutputStream out;
ObjectInputStream in;
String packet,ack,str, msg;
int n,i=0,sequence=0;
Sender(){}
public void run(){
try{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.println("Waiting for Connection....");


sender = new Socket("localhost",2004);
sequence=0;
out=new ObjectOutputStream(sender.getOutputStream());
out.flush();
in=new ObjectInputStream(sender.getInputStream());
str=(String)in.readObject();
System.out.println("reciver > "+str);
System.out.println("Enter the data to send....");
packet=br.readLine();
n=packet.length();
do{
try{
if(i<n){
msg=String.valueOf(sequence);
msg=msg.concat(packet.substring(i,i+1));
}
else if(i==n){
msg="end";out.writeObject(msg);break;
}
out.writeObject(msg);
sequence=(sequence==0)?1:0;
out.flush();
System.out.println("data sent>"+msg);
ack=(String)in.readObject();
System.out.println("waiting for ack.....\n\n");
if(ack.equals(String.valueOf(sequence))){
i++;
System.out.println("receiver > "+" packet recieved\n\n");
}
else{
System.out.println("Time out resending data....\n\n");
sequence=(sequence==0)?1:0;
}
}catch(Exception e){}
}while(i<n+1);
System.out.println("All data sent. exiting.");
}catch(Exception e){}
finally{
try{
in.close();
out.close();
sender.close();
}
catch(Exception e){}

}
}
public static void main(String args[]){
Sender s=new Sender();
s.run();
}
}
//RECEIVER PROGRAM
import java.io.*;
import java.net.*;
public class Reciever{
ServerSocket reciever;
Socket connection=null;
ObjectOutputStream out;
ObjectInputStream in;
String packet,ack,data="";
int i=0,sequence=0;
Reciever(){}
public void run(){
try{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
reciever = new ServerSocket(2004,10);
System.out.println("waiting for connection...");
connection=reciever.accept();
sequence=0;
System.out.println("Connection established :");
out=new ObjectOutputStream(connection.getOutputStream());
out.flush();
in=new ObjectInputStream(connection.getInputStream());
out.writeObject("connected .");
do{
try{
packet=(String)in.readObject();
if(Integer.valueOf(packet.substring(0,1))==sequence){
data+=packet.substring(1);
sequence=(sequence==0)?1:0;
System.out.println("\n\nreceiver
>"+packet);
}
else
{
System.out.println("\n\nreceiver
>"+packet +" duplicate data");
}
if(i<3){

out.writeObject(String.valueOf(sequence));i++;
}
else{
out.writeObject(String.valueOf((sequence+1)%2));
i=0;
}
}
catch(Exception e){}
}while(!packet.equals("end"));
System.out.println("Data recived="+data);
out.writeObject("connection ended .");
}
catch(Exception e){}
finally{
try{
in.close();
out.close();
reciever.close();
}
catch(Exception e){}
}
}
public static void main(String args[]){
Reciever s=new Reciever();
while(true){
s.run();
}
}
}

Conclusion: Thus we implemented Stop & wait protocol using sockets in java.

S-ar putea să vă placă și