ACN Lab manual-UPDATED
ACN Lab manual-UPDATED
NETWORKS
(ETIT-453)
B.Tech. Programme
(IT)
LAB MANUAL
CONTENTS
1. Introduction
4. List of Experiments
5. Detail of Experiments
7. References
1. INTRODUCTION
This course provides students with hands on training regarding the design, troubleshooting,
modeling and evaluation of computer networks. In this course, students are going to experiment
in a real test-bed networking environment, and learn about network design and troubleshooting .
The students will be using Cisco Packet Tracer networking tool and Java Network
programming.
Packet Tracer is a cross-platform visual simulation program designed by Cisco Systems that allows
users to create network topologies and imitate modern computer networks. The software allows
users to simulate the configuration of Cisco routers and switches using a simulated command line
interface. Packet Tracer makes use of a drag and drop user interface, allowing users to add and
remove simulated network devices as they see fit. Using this tool the students will be building
networking models and implementing various protocols that will help them evaluate their design
approaches and expected network performance. The students will be, assigning IP addresses to
various network devices, configuring router, configuring various protocols like ARP, RIP, BGP,
OSPF, configuring DHCP and FTP server.
The students will also be introduced to java network programming, where they will be creating
sockets for communication between two computers using TCP. A client program creates a socket
on its end of the communication and attempts to connect that socket to a server. When the
connection is made, the server creates a socket object on its end of the communication. The client
and server can now communicate by writing to and reading from the socket.
Some applications over the network will not require the reliable, point-to-point channel provided
by TCP. Rather, these applications might benefit from a mode of communication that delivers
independent packages of information whose arrival and order of arrival are not guaranteed. For
these applications, UDP protocol provides a mode of network communication which is also
implemented.
2. Lab Requirements
Marking Scheme:
Total Marks: 40
Punctuality/Attendance 10
Knowledge/Logic development/Status of the experiment 10
File (Organization and File checking status) 10
Viva Voce: 10
NOTE: In every lab, marks are awarded to the student out of 40 for each experiment performed
in the lab and at the end the average marks are given out of 40.
It is taken by the concerned faculty member of the batch and by an external examiner. In this
exam student needs to perform the experiment allotted at the time of the examination, a sheet
will be given to the student in which some details asked by the examiner needs to be written
and at last viva will be taken by the external examiner.
Marking Scheme:
Total Marks: 60
NOTE:
4. List of Experiments
5. Detail of Experiments
Experiment 1
INTRODUCTION
Cisco Packet Tracer is a powerful network simulation program that allows to experiment with
network behavior. It is an integral part of the Networking Academy comprehensive learning
experience; Packet Tracer provides simulation, visualization, authoring, assessment, and
collaboration capabilities.
Packet Tracer is simulator software that simulates router, switch and other networking
equipment. Cisco devices are expensive. Packet Tracer simulates all necessary equipment
thereby cost effective. Packet Tracer is developed by Cisco system. It’s a network simulation
program which can be used to design certain topologies and configure Routers, switches, PC,
etc and test a network and its functioning.
It provides good visualization and simulation, with ease of implementation and testing.
Packet Tracer Workspaces: Cisco Packet Tracer has two workspaces—logical and physical.
Logical Workspace: The logical workspace allows users to build logical network topologies
by placing, connecting, and clustering virtual network devices.
Physical Workspace: The physical workspace provides a graphical physical dimension of the
logical network, giving a sense of scale and placement in how network devices such as routers,
switches, and hosts would look in a real environment. The physical view also provides
geographic representations of networks, including multiple cities, buildings, and wiring closets.
It provides International language support and it is also compatible with the following
platforms: Windows, Windows XP; Vista (Vista Basic, Vista Premium); Windows 7; and
Linux (Ubuntu, Fedora)
It Enables visualization, animation, and detailed modeling for exploration and experimentation
and supports the majority of protocols and technologies.
Packet Tracer supports basic routing capabilities using RIP, OSPF and EIGRP.
With Cisco packet tracer the networking devices and be connected and tested for their working.
ROUTERS
A router provides connectivity between two logical networks. Every router in Packet Tracer
can be switched on or off by using the provided power button.
Cisco 1841: This is an Integrated Service Router (ISR) having two Fast Ethernet ports ,two
slots for High Speed WAN Interface Cards (HWICs), and one slot
,for Advanced Integration Module (AIM)
Cisco 1941: This is similar to the previous model but runs on Cisco IOS Version 15. It has two
ports that operate at Gigabit Ethernet speeds.
Cisco 2620XM: This is a multiservice router with one Fast Ethernet port, two slots for
WAN Interface cards, and one slot for AIM.
Cisco 2621XM: This is similar to the previous model, except that this router has two Fast
Ethernet ports.
Cisco 2811: This ISR comes with two Fast Ethernet ports, four WIC slots, and a dual slot
for AIM.
Cisco 2901: This router has two Gigabit Ethernet ports, four WIC slots, and two Digital
Signal Processor (DSP) slots. This router uses Cisco IOS Version 15.
Cisco 2911: This router has three Gigabit Ethernet ports and all the other features of the
previous router. It runs on IOS Version 15.
Generic Router-PT: This is a custom router running on Cisco IOS. It contains 10 slots and
has separate modules with a naming convention beginning with PT.
SWITCHES
A switch, also called a multiport bridge, connects more than two end devices together. Each
switch port is a collision domain.
Cisco 2950-24: This managed switch comes with 24 Fast Ethernet ports.
Cisco 2950T-24: This switch is a member of the Catalyst 2590 Intelligent Switch family and
has two Gigabit Ethernet ports in addition to the 24 Fast Ethernet ports.
Cisco 2960-24TT: This is another 24 port switch; the previous switch has Gigabit Interface
Converter (GBIC) for Gigabit Ethernet ports, whereas this switch
has Small Form-factor Pluggable (SFP) modules for the same.
Cisco 3560-24PS: This switch is different from the others because it is a layer 3 switch that
can be used to perform routing in addition to switching. The PS suffix
implies support for Power over Ethernet (PoE), which can be used to
power up IP phones without using power adapters.
Bridge PT: This is a device used to segment a NETWORK and it has only two ports
(which is why it is a bridge; if it had more, it'd be called a switch).
Generic Switch PT: This is a Packet-Tracer-designed switch running on Cisco IOS. This is
only customizable switch with 10 slots and several modules.
CONNECTORS
Console PC/Laptop/Generic to
Router/Switch
Experiment 2
We need to perform some initial configurations on router before it can be used for routing.
Cisco IOS supports various command modes, among those followings are the main command
modes.
User EXEC Mode
Privileged EXEC Mode
Global Configuration Mode
Interface Configuration Mode
Setup Mode
You need to execute specific commands to navigate from one mode to another.
User Exec mode => Privileged Exec mode => Global Configuration mode => Interface
Configuration mode => Sub Interface Configuration mode
Router will enter in setup mode only if it fails to load a valid running configuration.
Step 2. Click on the router and access CLI prompt of the router.
Step 3. Enter the following commands to configure, change hostname and secure the router
with a password.
configure terminal : Enters global configuration mode, when using the console port.
Router> enable
Router# configure terminal
Router(config)#
Command Description
Router(config-line) #exit
Router(config) #exit
Router #exit
OUTPUT :
After executing the above commands. Now your router (Lab1) is secured with a password.
Hostname are easy to remember. We can use host name instead of their IP address while
connecting with remote address. Router resolves IP address to hostname in two ways: static
andndynamic.
In static method we have to assign hostname to IP address.
In dynamic method we have to configure an external DNS server and need to configure its IP
address on router.
Show hosts command will display the currently configured hosts with their IP addresses.
Following are the steps to illustrate an example of static entry for hostname.
Router>enable
Router #configure terminal
Router(config) #ip host hostname ipaddress(eg. 202.12.21.4)
3. Now use show hosts command to display currently configured hosts with their IP address.
Experiment 3
Computers in a network have to be connected in some logical manner. The layout pattern of
the interconnections between computers in a network is called network topology.
Bus topology uses one main cable to which all nodes are directly connected. The main cable
acts as a backbone for the network. One of the computers in the network typically acts as the
computer server. Advantage of bus topology is that it is easy to connect a computer or
peripheral device. The second advantage is that the cable requirements are relatively small,
resulting in lower cost. This type of topology is not used for large networks.
1. First select three switch and three client and connect them by fast Ethernet wires
2. Configure the client by providing there IP address and subnet mask by going in
respective properties.
Fig.3.4 IP Configured
6. Select message from menu and pass it between any two clients if it becomes successful
than your connection is in working condition.
Star Topology:
1. Select a switch and 4 clients and connect them by fast Ethernet wires.
2. Provide a IP address and subnet mask in all 4 clients and that should be different from
each other
3. In IP address provide 192.168.1.1 and so on in all others PC. same i.e 255.255.255.0
Experiment 4
• IP address
• net mask
The Dynamic Host Configuration Protocol (DHCP) provides all the above functionalities of
BOOTP alongwith static and dynamic address allocation that can be manual or automatic.
1. Select one router, switch and number of clients for connection setup. And connect them
through fast Ethernet wire with each other.
Fig.4.1 Topology
2. Check the properties of each client by going in there config window after selecting DHCP
other than STATIC. It will return unable to connect. Because router is not set up.
R1#config t
R1(config)#interface fastethernet 0/0
R1(config-if)#ip address 192.168.1.1 255.255.255.0
R1(config-if)#no shutdown
R1(config-if)#exit
R1(config)#interface fastethernet 1/0
R1(config-if)#ip address 192.168.1.0 255.255.255.0
R1(config-if)#no shutdown
R1(config-if)#exit
R1(dhcp-config)#default-router 192.168.1.1
R1(dhcp-config)#exit
4. Now, Click on any of the PC > Desktop > IP configuration > Choose DHCP.
Experiment 5
Reverse ARP (RARP) as defined by RFC 903 works the same way as the Address Resolution
Protocol (ARP), except that the RARP request packet requests an IP address instead of a media
access control (MAC) address. RARP often is used by diskless workstations because this type
of device has no way to store IP addresses to use when they boot. The only address that is
known is the MAC address because it is burned in to the hardware. RARP requires a RARP
server on the same network segment as the device interface. The figure below illustrates how
RARP works.
3. Click on one of the device among which you want the connection.
PC>arp –a
PC>ping ipaddress(address of the destination )
5. Enter the simulation mode and edit filters by selecting only ARP & ICMP protocols.
9. Go back in the command prompt and again write arp -a command and you can see that
the connection has established and physical address is generated.
Static Routing:
Configure Static Routing is the routing that network administrator configure the network
routers manually, instead of using routing protocols, RIP or OSPF which used in the dynamic
routing. The benefits of static routing is minimum bandwidth usage, no overhead on router
CPU and many more and perfect for small network with a few routers. But it is not without
cons. Difficult to configure all routers manually in the large network and troubleshooting is
always harder than configuration.
IP route command is used to configure the static route. Static routes are the most secure way
of routing. They will also increase overall network performance. These features are extremely
helpful in small network.
Or
IP route:
This is the base command which adds new route in routing table.
destination_network_#[subnet_mask]:
This is the first parameter. It specifies the destination network address. We need to provide
subnet mask if we are using sub-network. Sub-networks are the smaller networks created from
one large network in subnetting. If we are not using sub-network then we can omit the subnet
mask value. It will parse automatically.
IP_address_of_next_hop_neighbor / interface_to_exit:
This parameter provides a way to reach the destination network. Both commands use separate
way to assign this value. First command provides the IP address of next hop neighbor. It tells
router that if it receives a packet for destination [that we set in previous parameter], forward
that packet to this next hop neighbor IP address.
Second command also do the same job but in different way. It specifies exit interface instead
of next hop IP address. It tells router that if it receives a packet for the destination specified by
previous parameter then exits that packet from this interface. Device attached on other end of
this interface will take care of the packet.
administrative_distance:
Administrative distance is the trustworthiness of route. Route with the lowest AD value will be
chosen while forwarding the packet. By default static route has two AD values depending on
the previous parameter. If you have used next hop neighbor IP address, then the default AD
value will be 1. If you have used exit interface, then the default AD value will be 0. This
parameter allows us to create multiple static routes for the same destination. For example we
can create primary and backup path for the destination network. To create backup path, we
need to set AD value to higher than default, such as 2 or 3. With this configuration router will
use primary path. Due to some reason if primary route fails, the router will start using backup
route automatically.
permanent:
When a route goes down router will remove that from routing table. Permanent parameter will
keep this route in routing table even if it goes down. Its optional parameter we can omit it. If
we omit it, router will remove this route from routing table if it goes down. You might use this
parameter for security reason if you never want packets to take another path.
Double click Router0 and click CLI and press Enter key to access command prompt of
router.
Two interfaces FastEthernet0/0 and Serial0/0/0 of Router0 are used in this topology.
By default interfaces on router are remain administratively down during the start up. We
need to configure IP address and other parameters on interfaces before we could actually
use them for routing. Interface mode is used to assign IP address and other parameters.
Interface mode can be accessed from global configuration mode. Following commands
are used to access global configuration mode.
Router>enable
Router#configure terminal
Enter configuration commands, one per line. End with CNTL/Z. Router(config)#
From global configuration mode we can enter in interface mode. From there we can
configure the interface. Following commands will assign IP address on FastEthernet0/0.
Serial interface needs two additional parameters clock rate and bandwidth. Every serial cable
has two ends DTE and DCE. These parameters are always configured at DCE end. We can use
show controllers interface command from privilege mode to check the cable's end.
Fourth line of output confirms that DCE end of serial cable is attached. If you see DTE here
instead of DCE skip these parameters.
Now we have necessary information let's assign IP address to serial interface. Following
commands are used:
Router#configure terminal
Enter configuration commands, one per line. End with CNTL/Z.
Router(config)#interface serial 0/0/0
Router(config-if)#ip address 192.168.0.253 255.255.255.252
Router(config-if)#clock rate 64000
Router(config-if)#bandwidth 64
Router(config-if)#no shutdown
Router(config-if)#exit
Router(config)#
Fig.5.16 exit
We will use same commands to assign IP addresses on interfaces of Router1. Since we have
provided clock rate and bandwidth on serial interface of Router0 we need not to assign them
on serial interface of Router1. Following command will assign IP addresses on interface of
Router1.
Now all the devices and interfaces have the following IP Address:
Router0
Router(config)#ip route 20.0.0.0 255.0.0.0 192.168.0.254
Router1
Router(config)#ip route 10.0.0.0 255.0.0.0 192.168.0.253
That's all we need to switch packet from one network to another. To verify the result we
can use ping command. Access the command prompt of PC1 and use ping command to
test the connectivity from PC0.
Experiment 6
Aim: To implement and configure RIP, OSPF and BGP routing protocols.
RIP Routing Protocol
RIP is a distance vector routing protocol. It shares routing information through the local
broadcast in every 30 seconds. RIP is a routing protocol which exchanges network information
between routers dynamically. It uses broadcast to share routing information.
In RIP protocol routers learn about the destination networks from neighboring routers through
the sharing process. Routers running RIP protocol periodically broadcast the configured
networks from all ports. Listing routers will update their routing table based on this
information.
In static method we have to update router manually. In dynamic method router will be
updated by a routing protocol.
Unlike static routing where we have to configure all routes manually, in dynamic routing all
we need to do is just tell the routing protocol which route we want to advertise. And rest will
be done automatically by running dynamic protocol. In our network we are running RIP routing
protocol so it will be handled by RIP.
RIP Protocol will share configured routes in network through the broadcasts. These broadcasts
are known as routing updates. Listening routers will update their routing table based on these
updates.
Router takes several measurements while processing and putting new route information in
routing table. If router discovers new route in update, it will put that in routing table.
Router will broadcast again with new routing information. This time routers have nothing to
update. This stage is known as convergence.
Convergence
Convergence is a term that refers to the time taken by all routers in understanding the current
topology of network.
2. Assign IP address to all the devices and interfaces as assigned earlier in practical 5.
3. After assigning IP address the devices and interfaces have the following IP address:
router rip command tell router to enable the RIP routing protocol.
network command allows us to specify the networks which we want to advertise. We only
need to specify the networks which are directly connected with the router.
That’s all we need to configure the RIP. Follow same steps on remaining routers.
Our network is ready to take the advantage of RIP routing. To verify the setup we will
use ping command. ping command is used to test the connectivity between two devices.
Access the command prompt of PC1 and use ping command to test the connectivity from
PC0.
7. Now trace the route from PC1 to PC0 using tracer ip address (destination) command.
OSPF stands for Open Shortest Path First. OSPF is a link state open standard based routing
protocol. It was created in mid-1980. Since it is based on open standard, we can use it with any
vendor’s router.
Disadvantages of OSPF:
It requires extra CPU process to run SPF algorithm.
It requires more RAM to store adjacency topology.
It is more complex to setup and hard to troubleshoot.
Basically OPSF was created to fulfill the requirement of enterprise size network. To scale a
large size network it uses area concept. Area concept is similar to Subnetting. It allows us to
separate the large internetwork into smaller networks known as areas.
OSPF routers share routing information only with neighbors. OSPF uses hello packets to
discover neighbors in segments. A hello packet contains some essential configuration values
that must be same on both routers who want to build an OSPF neighborship.
In order to become OSPF neighbor following values must be match on both routers.
Area ID
Authentication
Hello and Dead Intervals
Stub Flag
MTU Size
2. Assign IP address to all the devices and interfaces as assigned earlier in practical 5.
3. After assigning IP address the devices and interfaces have the following IP address:
This command will enable OSPF routing protocol in router. Process ID is a positive integer.
We can use any number from 1 to 65,535. Process ID is locally significant. We can run multiple
OSPF process on same router. Process ID is used to differentiate between them. Process ID
need not to match on all routers.
Network command allows us to specify the interfaces which we want to include in OSPF
process. This command accepts three arguments network number, wildcard mask and area
number.
Network number
Network number is network ID. We can use any particular host IP address or network IP
address. For example we can use 192.168.1.1 (host IP address) or we can use 192.168.1.0
(Network IP address). While targeting a specific interface usually we use host IP address
(configured on that interface).
Prepared by: Dr. Anupama Kaushik
Advanced Computer Networks Lab Manual ETIT-453
While targeting multiple interfaces, we use network IP address. So any interface that belongs
to specified network ID will be selected.
Wildcard mask
Wildcard mask are used with network ID to filter the interfaces. Wildcard mask is different
from subnet mask. Subnet mask is used to separate the network portion and host portion in IP
address. While wildcard mask is used to match corresponding octet in network portion.
Wildcard mask tells OSPF the part of network address that must be matched. Wildcard masks
are explained with examples in access list tutorials of this category.
Key points
0 (Decimal – octet format) Wildcard mask indicates that corresponding octet in network
address must be matched exactly.
255 (Decimal – octet format) Wildcard mask indicates that we don’t care about corresponding
octet in network address.
For example
0 (Binary – bit format) Wildcard mask indicates that corresponding bit in network address
must be matched exactly.
255 (Binary – bit format) Wildcard mask indicates that we don’t care about corresponding bit
in network address.
OSPF is a classless protocol. With wildcard we can also filter Subnetted networks. In classes
implementation usually we use Subnetted networks. For example consider following figure.
For example we want to exclude serial interfaces in above configuration. We can use a wildcard
mask of 0.0.0.255 to match the subnet mask of /24.
Above commands will ask router to match /24 bits of address instead of default /16 bits. Now
router will look for 172.168.1.x and 172.168.2.x network. Our serial interfaces have
172.168.3.0/24 and 172.168.4.0/24 networks which do not fall in these search criteria.
Let’s take one more example, if we use following network command, which interfaces would
be selected.
In this case valid host IP addresses are 192.168.0.1 and 192.168.0.2. So any interface that has
these IP address would be selected. /30 network is usually used for serial link connection which
need only two valid host IP addresses; one for each end.
7. Now trace the route from PC1 to PC0 using tracer ip address (destination).
BGP (Border Gateway Protocol) is the core routing protocol of the Internet. It is described as
a path vector protocol as BGP does not use traditional IGP (OSPF, EIGRP, RIP) metrics, but
makes routing decisions based on path, network policies and/or rule sets. It maintains a table
of IP networks or 'prefixes' which designate network reach ability among autonomous systems
(AS).
3. Configure BGP routing protocol for all the routers using the following commands.
Prepared by: Dr. Anupama Kaushik
Advanced Computer Networks Lab Manual ETIT-453
4. After configuring BGP, use BGP verification commands to verify your configuration
Router#show ip bgp
Experiment 7
1. Select one router, two switches, and two clients and one server & name that server as FTP.
2. Select a module in a router, keep it in mind server must be switched OFF while installing
module, and ON it after installation of module.
3. Connect each module with one another through wires. (As shown in first figure of this
Exp.)
4. After this, click on server and select IP configuration tab in that, where you will provide
IP address i.e. 192.168.1.2, subnet mask 255.255.255.0 & gateway IP address 192.168.1.1
Fig.7.3. IP Configuration
5. Click on server again and then click on config and there you select FTP and provide
username and password of your own choice, also select all the checkboxes provided below
and after that click on ADD.
6. After doing settings in server click on first client and select IP configuration tab in that
where you will provide IP address: 192.168.2.2 and subnet mask is 255.255.255.0 &
gateway IP address is 192.168.2.1
7. Similarly for second client also you will repeat the step no.6 but in second client you will
change the IP address to 192.168.3.2 and subnet mask will be the same, while gateway IP
address will changed to 192.168.3.1
8. Click on router and click on “config” tab of it, select Fastethernet 0/0 and put the port
status “ON” also provide a IP address 192.168.2.1 and subnet mask 255.255.255.0.
Similarly in Fastethernet 1/0 repeat this step, just there will be a change in IP address that
is 192.168.3.1. while in Fastethernet 6/0 IP address will be changed to 192.168.1.1
9. Now select first client and click on “command prompt” tab of that, and write a code as
shown in a figure.
10. Once the file transfer is successful, your connection is correctly connected.
The next three programs are on Java Network Programming. The term network programming
refers to writing programs that execute across multiple devices (computers), in which the
devices are all connected to each other using a network.
The java.net package of the J2SE APIs contains a collection of classes and interfaces that
provide the low-level communication details, allowing us to write programs that focus on
solving the problem at hand.
The java.net package provides support for the two common network protocols:
TCP: TCP stands for Transmission Control Protocol, which allows for reliable
communication between two applications. TCP is typically used over the Internet
Protocol, which is referred to as TCP/IP.
UDP: UDP stands for User Datagram Protocol, a connection-less protocol that allows
for packets of data to be transmitted between applications.
In Network Programming we will be using sockets. A socket is a connection between two hosts. It
can perform seven basic operations:
TCP Sockets
Java’s Socket class is used by both clients and servers and has methods that correspond
to the first four of these operations. The last three operations are needed only by servers,
which wait for clients to connect to them. They are implemented by the ServerSocket class.
The java.net.Socket class is Java’s fundamental class for performing client-side TCP
operations. Other client oriented classes that make TCP network connections such as
The constructors
Each lets you specify the host and the port you want to connect to. Hosts may be specified as
an InetAddress or a String. Ports are always specified as int values from 0 to 65,535. Two of
the constructors also specify the local address and local port from which data will be sent.
This constructor creates a TCP socket to the specified port on the specified host and
attempts to connect to the remote host. For example:
try
{
Socket soc = new Socket(www.google.com,80)
}
Catch(UnknownHostException ex)
{
System.err.println(ex);
}
Catch(IOException ex)
{
System.err.println(ex);
}
This constructor differs by using an InetAddress object to specify the host rather than a
hostname.
try
{
InetAddress soc = InetAddress.getbyname(“domain name”)
Socket soc = new Socket (domain name,80)
}
Catch(UnknownHostException ex)
{
System.err.println(ex);
Prepared by: Dr. Anupama Kaushik
Advanced Computer Networks Lab Manual ETIT-453
}
Catch(IOException ex)
{
System.err.println(ex);
}
There are no public constructors in the InetAddress class. However, InetAddress has three
static methods that return suitably initialized InetAddress objects given a little information.
They are:
Throws UnknownHostException
Throws UnknownHostException
Throws UnknownHostException
All three of these methods may make a connection to the local DNS server to fill out the
information in the InetAddress object. This has a number of possibily unexpected implications,
among them that these methods may throw security expectations if the connection to the DNS
server is prohibited.Futhermore, invoking one of these methods may cause a host that uses a
PPP connection to dial into its provider if it isn’t already connected.The other methods in this
class, such as getAddress() and getHostName(), mostly work with the information provided by
one of these three methods.
Given a Socket object ,the getInetAddress() method tells you which remote host the Socket is
connected to or, if the connection is closed , which host the Socket was connected to when it
was connected. For example:
The getport() method tells you which port the Socket is connected to on the remote host.
The getport() method tells you which port the Socket is connected to on the remote host.
The getlocalAddress() method tells you which network interface a socket is bound to. We
normally use this on a multihomed host or one with multiple network interfaces.
The ServerSocket class contains everything needed to write servers in Java. It has
constructors that create new ServerSocket objects , methods that list for connections on a
specified port, methods that configure the various server socket options, and the usual
miscellaneous methods such as toString().
A new ServerSocket is created on a particular port using a ServerSocket()
constructor.
The ServerSocket listens for incoming connection attempts on that port using its
accept() method. Accept() blocks until a client attemts to make a connection, at which
point accept() returns a Socket object connecting the client and the server.
Depending on the type of server, either the Socket’s getInputStream() method,
getOutputStream() method, or both are called to get input and output streams that
communicate with the client.
The server and the client interact according to an agreed-upon protocol until it is time
to close the connection.
The server, the client, or both close the connection.
The server returns to step 2 and waits for the next connection.
The Constructors
throws IOException
These constructors let you specify the port, the length of the queue used to hold incoming
connection requests, and the local network interface to bind to. They pretty much all do the
same thing, though some use default values for the queue length and the address to bind to.
A ServerSocket customarily operates in a loop the repeatedly accepts connections. Each pass
through the loop invokes the accept() method. This returns a Socket object representing the
connection between the remote client and the local server. Interaction with the client takes
place through this Socket object. When the transaction is finished, the server should invoke
the Socket object’s close() method. If the client closes the connection while the server is still
operating, the input and/or output streams the connect the server to the client throw an
Interrupted IO Exception on the next read or write. In either case, the server should then get
ready to process the next incoming connection. However, when the server needs to shut down
and not process any further incoming connections, you should invoke the ServerSocket
object’s close() method.
Java’s Implementation of UDP is split into two classes: DatagramPacket and DatagramSocket.
The DatagramPacket class stuffs bytes of data into UDP packets called datagrams and lets you
unstuff datagrams that you receive. A DatagramSocket send as well as receives UDP
datagrams. To send data, you put data in DatagramPacket and send the packet using
DatagramSocket. To receive data, you receive a DatagramPacket object from a
DatagramSocket and then read the contents of the packet. In UDP, everything about a datagram,
including the address to which it is directed , is included in the packet itself; the socket only
needs to know the local port on which to listen or send.
This class provides methods to get and set the source or destination address from the IP header,
to get and set the source or destination port, to get and set the data, and to get and set the length
of the data.
These two constructors create new DatagramPacket objects for receiving data from the
network:
When a socket receives a datagram, it stores the datagram’s data part in buffer beginning at
buffer[0] and continuing until the packet is completely stored or until length bytes have been
written into the buffer. If the second constructor is used, storage begins at buffer[offset] instead.
Prepared by: Dr. Anupama Kaushik
Advanced Computer Networks Lab Manual ETIT-453
Otherwise these two constructors are identical. Length must be less than or equal to
buffer.length-offset. If you try to construct a DatagramPacket with a length that will overflow
the buffer, the constructor throws an Illegal Argument Exception. This is a Runtime Exception,
so your code is not required to catch it.
These four constructors create new DatagramPacket objects for sending data across the network
.
public DatagramPacket (byte[] data, int length, InetAddress destination, int port)
public DatagramPacket (byte[] data, int offset, int length, InetAddress
destination, int port) // java 1.2
public DatagramPacket (byte[] data, int length, SocketAddress destination, int
port) //java 1.4
public DatagramPacket (byte[] data, int offset , int length, SocketAddress
destination, int port) //java 1.4
Each constructor creates a new DatagramPacket to be sent to another host. The packet is filled
with length bytes of the data array starting at offset or 0 if offset is not used. If you try to
construct a Datagram Packet with a length that is greater than data.length, the constructor
throws an IllegalArgumentException.
DatagramPacket has six methods that retrieve different parts of a datagram: the actual data plus
several fields from its header. These methods are mostly used for datagrams received from the
network.
The getAddress() method returns an InetAddress object containing the address of the remote
host. If the datagram was received from the Internet, the address returned is the address of the
Prepared by: Dr. Anupama Kaushik
Advanced Computer Networks Lab Manual ETIT-453
machine that sent it (the source address). On the other hand, if the datagram was created locally
to be sent to a remote machine, this method returns the address of the host to which the
datagram is addressed ( the destination address). This method is most commonly used to
determine the address of the host that sent a UDP datagram, so that the recipient can reply.
The getPort() method returns an integer specifying the remote port. If this datagram was
received from the Internet, this is the port on the host that sent the packet. If the datagram was
created locally to be sent to a remote host, this is the port to which the packet is addressed on
the remote machine.
The getSocketAddress() method returns a SocketAddress object containing the IP address and
port of the remote host.
The getData() method returns a byte array containing the data from the datagram.
The getLength() method returns the number of bytes of data in the datagram.
This method simply returns the point in the array returned by getData() where the data
from the datagram begins.
Most of the time, the six constructors are sufficient for creating datagrams. However,
Java also provides several methods for changing the data, remote address, and remote
port after the datagram has been created.
The setData() method changes the payload of the UDP datagram. You might use this
method if you are sending a large file to a remote host.
public void setData(byte[] data, int offset, int length) // Java 1.2
The setAddress() method changes the address a datagram packet is sent to.
The setSocketAddress() method changes the address and port a datagram packet is sent
to.
The setLength() method changes the number of bytes of data in the internal buffer that
are considered to be part of the datagram’s data as opposed to merely unfilled space.
The Constructors
The DatagramSocket constructors are used in different situations, much like the
DatagramPacket constructors. The first constructor opens a datagram socket on an
anonymous local port. The second constructor opens a datagram socket on a well known
local port that listens to all local network interfaces. The third constructor opens a
datagram socket on a well known local port on a specific network interface. Java 1.4
adds a constructor that allows this network interface and port to be specified with a
SocketAddress. Java 1.4 also adds a protected constructor that allows you to change the
implementation class. All five constructors deal only with the local address and port.
The remote address and port are stored in the DatagramPacket, not the DatagramSocket.
This constructor creates a socket that is bound to an anonymous port. For example :
try {
DatagramSocket client = new DatagramSocket();
// send packets…
}
Catch (SocketException ex) {
System.err.println(ex);
}
You would use this constructor in a client that initiates a conversation with a server.
This constructor creates a socket that listens for incoming datagrams on a particular
port, specified by the port argument. Use this constructor to write a server that listens
on a well known port; if servers listened on anonymous ports, clients would not be able
to contact them. A SocketException is thrown if the socket can’t be created.
This constructor is primarily used on multihomed hosts; it creates a socket that listens
for incoming datagrams on a specific port and network interface. This port argument is
the port on which this socket listens for datagrams.
This constructor is similar to the previous one except that the network interface address
and port are read from a SocketAddress.
This constructor enables subclasses to provide their own implementation of the UDP
protocol, rather than blindly accepting the default.
The primary task of the DatagramSocket class is to send and receive UDP datagrams.
One socket can both send and receive from multiple hosts at the same time.
thesocket.send(theoutput);
This method receives a single UDP datagram from the network and stores it in the
preexisting DatagramPacket object dp.
Experiment 8
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
Experiment 9
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.Socket;
Experiment 10
import java.net.*;
import java.io.*;
public class client
{
public static void main(String args[])throws Exception
{
byte b[]=new byte[1024];
FileInputStream f=new FileInputStream("D:/raj.txt");
DatagramSocket dsoc=new DatagramSocket(2000);
int i=0;
while(f.available()!=0)
{
b[i]=(byte)f.read();
i++;
}
f.close();
dsoc.send(new DatagramPacket(b,i,InetAddress.getLocalHost(),1000));
}
import java.net.*;
import java.io.*;
public class server
{
public static void main(String args[])throws IOException
{
byte b[]=new byte[3072];
DatagramSocket dsoc=new DatagramSocket(1000);
FileOutputStream f=new FileOutputStream("D:/nandha.txt");
while(true)
{
DatagramPacket dp=new DatagramPacket(b,b.length);
Prepared by: Dr. Anupama Kaushik
Advanced Computer Networks Lab Manual ETIT-453
dsoc.receive(dp);
System.out.println(newString(dp.getData(),0,dp.getLength()));
}
}
}
1. What is a Link?
2. What is a point to point link?
3. What is anonymous FTP??
4. How does a network topology affect your decision in setting up a network?
5. What is RIP?
6. What is NIC?
7. How many layers are there under TCP/IP?
8. What is the main purpose of OSPF?
9. What are firewalls?
10. What are gateways?
11. What are the functions of a network administrator?
12. What is Hybrid Network?
13. What is DHCP?
14. What is the main job of the ARP?
15. What is netstat?
16. What is tracert?
17. What is Ping?
18. What protocols fall under the TCP/IP Internet Layer?
19. What is IPv6?
20. What is multicast routing ?
21. Describe Ethernet.
22. When you move the NIC cards from one PC to another PC, does the MAC address gets
transferred as well?
23. What is ipconfig?
24. What is the difference between a straight-through and crossover cable?
25. What is the difference between a hub and a switch?
7. REFERENCES
[1]. http://www.cisco.com
[2]. http://www.packettracernetwork.com/tutorials/video-tutorials.html
[3]. Elliotte Rusty Harold, " Java Network Programming", O'Reilly Media 2013.