CS3591-CN Lab Manual
CS3591-CN Lab Manual
LAB MANUAL
CS3591–COMPUTER NETWORKS
Year/Semester: III/ V
1. Learn to use commands like tcpdump, netstat, ifconfig, nslookup and traceroute. Capture ping
and trace route PDUs using a network protocol analyzer and examine.
2. Write a HTTP web client program to download a web page using TCP sockets.
3. Applications using TCP sockets like: a) Echo client and echo server b) Chat
5. Use a tool like Wireshark to capture packets and examine the packets
7. Study of Network simulator (NS) and Simulation of Congestion Control Algorithms using NS.
COURSE OUTCOMES: At the end of this course, the students will be able to:
CO’s-PO’s&PSO’sMAPPING
PO’s PSO’s
CO’s 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3
1 3 1 2 3 - - - - 1 1 3 1 3 2 1
2 3 2 1 2 2 - - - 2 2 2 1 3 2 3
3 2 2 3 2 1 - - - 3 3 1 2 1 1 3
4 1 3 1 3 1 - - - 1 2 1 1 1 3 1
5 3 3 1 1 2 - - - 2 2 2 2 2 2 2
AVG 2 2 2 2 2 - - - 2 2 2 1 2 2 2
1-low,2-medium,3-high,‘-'-nocorrelation
LIST OF EXPERIMENTS
Write a HTTP web client program to download a web page using TCP
2
sockets.
3 Applications using TCP sockets like Echo Client and Echo Server
10 Use a tool like Wireshark to capture packets and examine the packets
To learn commands like tcpdump, netstat, ipconfig, nslookup, traceroute and ping.
Tcpdump
tcpdump offers interesting insights into network behavior. To have a quick look into the network
traffic passing by the network interface of a computer, tcpdump is a good choice.
It dumps packets directly from the network interface and displays it human-friendly in the
terminal. In the ComNetsEmu, there are several examples and situations where GUI-programs
cannot be used to display the traffic between the emulated hosts, so tcpdump can be useful for
those scenarios. To be able to capture all traffic and not only traffic destined for the current
computer network interfaces, the listening interface has to support the so-called monitoring
(promiscuous) mode, which has to be established beforehand. For a first quick look, we can start
without any parameters. It will monitor the default interface for connecting to the Internet. Most
common used parameters for capture include:
-#
A packet number is printed on every line.
-c
Exit the dump after the specified number of packets.
-D
Print all available interfaces for capture.
-e
Print also the link-layer header of a packet (e.g., to see the vlan tag).
-i
Interface to dump from (e.g., eth0 or in the example enp0s31f6).
-n
Do not resolve the addresses to names (e.g., IP reverse lookup).
-q
Shorter output (for small terminals).
-v
Be a little bit verbose to see more packet information.
-w
Write the captured traffic to a file.
Netstat
Displays active TCP connections, ports on which the computer is listening, Ethernet statistics,
the IP routing table, IPv4 statistics (for the IP, ICMP, TCP, and UDP protocols), and IPv6
statistics (for the IPv6, ICMPv6, TCP over IPv6, and UDP over IPv6 protocols). Used without
parameters, this command displays active TCP connections.
Syntax
netstat [-a] [-b] [-e] [-n] [-o] [-p <Protocol>] [-r] [-s] [<interval>]
Parameters
Parameter Description
-a Displays all active TCP connections and the TCP and UDP ports on which the
computer is listening.
-b Displays the executable involved in creating each connection or listening port. In some
cases well-known executables host multiple independent components, and in these
cases the sequence of components involved in creating the connection or listening port
is displayed. In this case the executable name is in [] at the bottom, on top is the
component it called, and so forth until TCP/IP was reached. Note that this option can be
time-consuming and will fail unless you have sufficient permissions.
-e Displays Ethernet statistics, such as the number of bytes and packets sent and received.
This parameter can be combined with -s.
-n Displays active TCP connections, however, addresses and port numbers are expressed
numerically and no attempt is made to determine names.
-o Displays active TCP connections and includes the process ID (PID) for each
connection. You can find the application based on the PID on the Processes tab in
Windows Task Manager. This parameter can be combined with -a, -n, and -p.
-p <Protocol> Shows connections for the protocol specified by Protocol. In this case, the Protocol can
be tcp, udp, tcpv6, or udpv6. If this parameter is used with -s to display statistics by
protocol, Protocol can be tcp, udp, icmp, ip, tcpv6, udpv6, icmpv6, or ipv6.
-s Displays statistics by protocol. By default, statistics are shown for the TCP, UDP,
ICMP, and IP protocols. If the IPv6 protocol is installed, statistics are shown for the
TCP over IPv6, UDP over IPv6, ICMPv6, and IPv6 protocols. The -p parameter can be
used to specify a set of protocols.
-r Displays the contents of the IP routing table. This is equivalent to the route print
command.
<interval> Redisplays the selected information every interval seconds. Press CTRL+C to stop the
redisplay. If this parameter is omitted, this command prints the selected information
only once.
/? Displays help at the command prompt.
Remarks
Parameter Description
Proto The name of the protocol (TCP or UDP).
Local The IP address of the local computer and the port number being used. The name of the
address local computer that corresponds to the IP address and the name of the port is shown
unless the -n parameter is specified. If the port is not yet established, the port number is
shown as an asterisk (*).
Foreign The IP address and port number of the remote computer to which the socket is
address connected. The names that corresponds to the IP address and the port are shown unless
the -n parameter is specified. If the port is not yet established, the port number is shown
as an asterisk (*).
State Indicates the state of a TCP connection, including:
o CLOSE_WAIT
o CLOSED
o ESTABLISHED
o FIN_WAIT_1
o FIN_WAIT_2
Parameter Description
o LAST_ACK
o LISTEN
o SYN_RECEIVED
o SYN_SEND
o TIMED_WAIT
Examples
To display both the Ethernet statistics and the statistics for all protocols, type:
netstat -e -s
To display the statistics for only the TCP and UDP protocols, type:
netstat -s -p tcpudp
To display active TCP connections and the process IDs every 5 seconds, type:
netstat -o 5
To display active TCP connections and the process IDs using numerical form, type:
netstat -n -o
Ipconfig
Displays all current TCP/IP network configuration values and refreshes Dynamic Host
Configuration Protocol (DHCP) and Domain Name System (DNS) settings. Used without
parameters, ipconfig displays Internet Protocol version 4 (IPv4) and IPv6 addresses, subnet
mask, and default gateway for all adapters.
ipconfig
ipconfig /all
nslookup
The main use of nslookup is for troubleshooting DNS related problems or for security
reasons. Such reasons include guard against phishing attacks, in which a domain name is altered
-- for example, by substituting the numeral 1 for a lowercase l -- to make an unfriendly site look
friendly and familiar (joes1owerprices.com vs. joeslowerprices.com).
DNS, or nslookup, also helps deter cache poisoning, in which data is distributed to
caching resolvers, posing as an authoritative origin server.
Using Nslookup
nslookup www.google.com
To use in non-interactive mode type nslookup options at the command prompt.
To use in interactive mode type nslookup at the command line and hit return.
tracert
The traceroute command attempts to trace the route an IP packet follows to an Internet host by
launching UDP probe packets with a small maximum time-to-live (Max_ttl variable), then
listening for an ICMP TIME_EXCEEDED response from gateways along the way. Probes are
started with a Max_ttl value of one hop, which is increased one hop at a time until
anICMP PORT_UNREACHABLE message is returned.
The ICMP PORT_UNREACHABLE message indicates either that the host has been located or
the command has reached the maximum number of hops allowed for the trace.
The traceroute command sends three probes at each Max_ttl setting to record the following:
• Max_ttl value
• Address of the gateway
• Round-trip time of each successful probe
• Ping
• Usage: ping [-t] [-a] [-n count] [-l size] [-f] [-i TTL] [-v TOS] [-r count] [-s count] [[-j
host-list] | [-k host-list]] [-w timeout] [-R] [-S srcaddr] [-c compartment] [-p] [-4] [-6]
target_name
• Options:
• -t Ping the specified host until stopped.
• To see statistics and continue - type Control-Break;
• To stop - type Control-C.
• -a Resolve addresses to hostnames.
• -n count Number of echo requests to send.
• -l size Send buffer size.
• -f Set Don't Fragment flag in packet (IPv4-only).
• -i TTL Time To Live.
• -v TOS Type Of Service (IPv4-only. This setting has been deprecated
• and has no effect on the type of service field in the IP
• Header).
• -r count Record route for count hops (IPv4-only).
• -s count Timestamp for count hops (IPv4-only).
• -j host-list Loose source route along host-list (IPv4-only).
• -k host-list Strict source route along host-list (IPv4-only).
• -w timeout Timeout in milliseconds to wait for each reply.
• -R Use routing header to test reverse route also (IPv6-only).
• Per RFC 5095 the use of this routing header has been
deprecated. Some systems may drop echo requests if this header is used.
-S srcaddr Source address to use.
-c compartment Routing compartment identifier.
-p Ping a Hyper-V Network Virtualization provider address.
-4 Force using IPv4.
-6 Force using IPv6.
Ping is a computer network administration software utility used to test the reachability of
a host on an Internet Protocol (IP) network. It is available for virtually all operating systems that
have networking capability, including most embedded network administration software.
Ping measures the round-trip time for messages sent from the originating host to a
destination computer that are echoed back to the source. The name comes from active
sonar terminology that sends a pulse of sound and listens for the echo to detect objects under
water.
Ping operates by means of Internet Control MessageProtocol(ICMP) packets.
Pinging involves sending an ICMP echo request to the target host and waiting for an ICMP
echo reply. The program reports errors, packet loss, and a statistical summary of the results,
typically including the minimum, maximum, the mean round-trip times, and standard
deviation of the mean.
The command-line options of the ping utility and its output vary between the numerous
implementations. Options may include the size of the payload, count of tests, limits for the
number of network hops (TTL) that probes traverse, interval between the requests and time to
wait for a response. Many systems provide a companion utility ping6, for testing on Internet
Protocol version 6 (IPv6) networks, which implement ICMPv6.
Result:
Thus the commands like tcpdump, netstat, ipconfig, nslookup, tracert and ping was learnt
and used successfully.
Ex. No: 2 Write a HTTP web client program to download a web page using TCP
sockets
Aim:
To write a HTTP web client program to download a web page using TCP sockets.
Algorithm:
1. Start the program.
2. Get the frame size from the user
3. To create the frame based on the user request.
4. To send frames to server from the client side.
5. If your frames reach the server it will send ACK signal to client otherwise it will send
NACK signal to client.
6. Stop the program
Program:
import java.io.*;
import java.net.*;
public class SocketHTTPClient
{
public static void main(String[] args)
{
String hostName = "www.martinbroadhurst.com";
int portNumber = 80;
try{
Socket socket = new Socket (hostName, portNumber);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in =new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.println("GET / HTTP/1.1\nHost: www.martinbroadhurst.com\n\n");
String inputLine;
while((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}
} catch(UnknownHostException e) {
System.err.println("Don't know about host "+ hostName);
System.exit(1);
} catch(IOException e) {
System.err.println("Couldn't get I/O for the connection to "+
hostName);
System.exit(1);
}
}
}
Output :
Result:
Thus the HTTP web client program was executed successfully for downloading a
webpage.
Ex. No: 3 Applications using TCP sockets like Echo client and Echo server
Aim:
To write a java program for applications using TCP sockets like Echo client and Echo
server.
Algorithm:
Program:
EchoServer.Java:
import java.io.*;
import java.net.*;
public class EchoServer
{
public EchoServer(int portnum)
{
try
{
server = new ServerSocket(portnum);
}
catch (Exception err)
{
System.out.println(err);
}
}
public void serve()
{
try
{
while (true)
{
Socket client = server.accept();
BufferedReader r = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter w = new PrintWriter(client.getOutputStream(), true);
w.println("Welcome to the Java EchoServer. Type 'bye' to close.");
String line;
do
{
line = r.readLine();
if ( line != null )
w.println("Got: "+ line);
System.out.println (line);
}
while ( !line.trim().equals("bye") );
client.close();
}
}
catch (Exception err)
{
System.err.println(err);
}
}
public static void main(String[] args)
{
EchoServer s = new EchoServer(9999);
s.serve();
}
private ServerSocket server;
}
EchoClient.java :
import java.io.*;
import java.net.*;
public class EchoClient
{
public static void main(String[] args)
{
try
{
Socket s = new Socket("127.0.0.1", 9999);
BufferedReader r = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter w = new PrintWriter(s.getOutputStream(), true);
BufferedReader con = new BufferedReader(new InputStreamReader(System.in));
String line;
do {
line = r.readLine();
if ( line != null )
System.out.println(line);
line = con.readLine();
w.println(line);
}
while ( !line.trim().equals("bye") );}
catch (Exception err)
{
System.err.println(err);
}
}
}
Output :
Result:
Thus the java program to concurrently communicate using TCP Sockets was executed
successfully.
Ex.No:4 Simulation of DNS using UDP sockets
Aim:
Algorithm:
Program:
#UDP DNS Server
import java.io.*;
import java.net.*;
public class dnsserver
{
private static int indexOf(String[] array, String str)
{
str = str.trim();
for (int i=0; i<array.length; i++)
{
if (array[i].equals(str)) return i;
}
return -1;
}
public static void main(String arg[])throws IOException
{
String[] hosts = {"zoho.com", "gmail.com","google.com", "facebook.com"};
Aim:
To write a java program for simulating ARP protocols using TCP
Algorithm:
Client
1. Start the program
2. Using socket connection is established between client and server.
3. Get the IP address to be converted into MAC address.
4. Send this IP address to server.
5. Server returns the MAC address to client.
Server
Client:
import java.io.*;
import java.net.*;
import java.util.*;
class Clientarp
{
public static void main(String args[])
{
try
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
Socket clsct=new Socket("127.0.0.1",5604);
DataInputStream din=new DataInputStream(clsct.getInputStream());
DataOutputStreamdout=newDataOutputStream(clsct.getOutputStream());
System.out.println("Enter the Logical address(IP):");
String str1=in.readLine();
dout.writeBytes(str1+'\n');
String str=din.readLine();
System.out.println("The Physical Address is: "+str);
clsct.close();
}
catch (Exception e)
{ System.out.println(e);
}
}
}
Server:
import java.io.*;
import java.net.*;
import java.util.*;
class Serverarp
{
public static void main(String args[])
{
try
{
ServerSocketobj=new ServerSocket(5604);
Socket obj1=obj.accept();
while(true)
{
DataInputStream din=new DataInputStream(obj1.getInputStream());
DataOutputStreamdout=new DataOutputStream(obj1.getOutputStream());
String str=din.readLine();
String ip[]={"165.165.80.80","165.165.79.1"};
String mac[]={"6A:08:AA:C2","8A:BC:E3:FA"};
for(int i=0;i<ip.length;i++)
{
if(str.equals(ip[i]))
{
dout.writeBytes(mac[i]+'\n');
break;
}
}
obj.close();
}
}
catch(Exception e)
{
System.out.println(e);
}
}}
Result:Thus the ARP protocol using TCP Sockets program was executed successfully.
Ex. No:5(ii) Simulation of Reverse Address Resolution Protocol (RARP) using UDP
Aim:
To write a java program for simulating RARP protocols using UDP.
Algorithm:
Client
1. Start the program
2. Using datagram sockets UDP function is established.
3. Get the MAC address to be converted into IP address.
4. Send this MAC address to server.
5. Server returns the IP address to client.
Server
1. Start the program.
2. Server maintains the table in which IP and corresponding MAC addresses are stored.
3. Read the MAC address which is send by the client.
4. Map the IP address with its MAC address and return the IP address to client.
Program:
Client
import java.io.*;
import java.net.*;
import java.util.*;
class Clientrarp
{
public static void main(String args[])
{
try
{
DatagramSocket client=new DatagramSocket();
InetAddress addr=InetAddress.getByName("127.0.0.1");
byte[] sendbyte=new byte[1024];
byte[] receivebyte=new byte[1024];
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Physical address (MAC):");
String str=in.readLine(); sendbyte=str.getBytes();
DatagramPacket sender=new DatagramPacket(sendbyte,sendbyte.length,addr,1309);
client.send(sender);
DatagramPacket receiver=new DatagramPacket(receivebyte,receivebyte.length);
client.receive(receiver);
String s=new String(receiver.getData());
System.out.println("The Logical Address is(IP): "+s.trim());
client.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Server:
import java.io.*;
import java.net.*;
import java.util.*;
class Serverrarp
{
public static void main(String args[])
{
try
{
DatagramSocket server=new DatagramSocket(1309);
while(true)
{
byte[] sendbyte=new byte[1024];
byte[] receivebyte=new byte[1024];
DatagramPacket receiver=new DatagramPacket(receivebyte,receivebyte.length);
server.receive(receiver);
String str=new String(receiver.getData());
String s=str.trim();
InetAddress addr=receiver.getAddress();
int port=receiver.getPort();
String ip[]={"165.165.80.80","165.165.79.1"};
String mac[]={"6A:08:AA:C2","8A:BC:E3:FA"};
for(int i=0;i<ip.length;i++)
{
if(s.equals(mac[i]))
{
sendbyte=ip[i].getBytes();
DatagramPacket sender=new DatagramPacket(sendbyte,sendbyte.length,addr,port);
server.send(sender);
break;
}
}
break;
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Result:
Aim:
To study the network simulator (NS).
Introduction:
NS (from network simulator) is a name for series of discrete event network simulators,
specifically ns-1, ns-2 and ns-3. All of them are discrete-event network simulator, primarily used
in research and teaching. ns-3 is free software, publicly available under the GNU GPLv2 license
for research, development, and use.
The goal of the ns-3 project is to create an open simulation environment for networking
research that will be preferred inside the research community
• It should be aligned with the simulation needs of modern networking research.
• It should encourage community contribution, peer review, and validation of the
software.
Since the process of creation of a network simulator that contains a sufficient number of
High quality validated, tested and actively maintained models requires a lot of work, ns-3 project
spreads this workload over a large community of users and developers.
ns-1
The first version of ns, known as ns-1, was developed at VJ,GEEKLIME, Madurai
(LBNL) in the 1995-97 timeframe by Steve McCanne, Sally Floyd, Kevin Fall, and other
contributors. This was known as the LBNL Network Simulator, and derived from an earlier
simulator known as REAL by S. Keshav. The core of the simulator was written in C++, with
Tcl-based scripting of simulation scenarios. Long-running contributions have also come from
Sun Microsystems, the UC Berkeley Daedelus, and Carnegie Mellon Monarch projects.it used.
ns-2
In 1996-97, ns version 2 (ns-2) was initiated based on a refactoring by Steve McCanne.
Use of Tcl was replaced by MIT's Object Tcl (OTcl), an object-oriented dialect Tcl. The core of
ns-2 is also written in C++, but the C++ simulation objects are linked to shadow objects in OTcl
and variables can be linked between both language realms. Simulation scripts are written in the
OTcl language, an extension of the Tcl scripting language. Presently, ns-2 consists of over
300,000 lines of source code, and there is probably a comparable amount of contributed code
that is not integrated directly into the main distribution (many forks of ns-2 exist, both
maintained and unmaintained). It runs on GNU/Linux, FreeBSD, Solaris, Mac OS X and
Windows versions that support Cygwin. It is licensed for use under version 2 of the GNU
General Public License.
ns-3
A team led by Tom Henderson, George Riley, Sally Floyd, and Sumit Roy, applied for
and received funding from the U.S. National Science Foundation (NSF) to build a replacement
for ns-2, called ns-3. This team collaborated with the Planete project of INRIA at Sophia
Antipolis, with Mathieu Lacage as the software lead, and formed a new open source project.In
the process of developing ns-3, it was decided to completely abandon backwardcompatibility
with ns-2. The new simulator would be written from scratch, using the C++ programming
language. Development of ns-3 began in July 2006. A framework for generating Python bindings
(pybindgen) and use of the Waf build system were contributed by Gustavo Carneiro. The first
release, ns-3.1 was made in June 2008, and afterwards the project continued making quarterly
software releases, and more recently has moved to three releases per year. ns-3 made its
eighteenth release (ns-3.18) in the third quarter of 2013.
Design
ns-3 is built using C++ and Python with scripting capability. The ns-3 library is wrapped
to python. Thanks to the pybindgen library which delegates the parsing of the ns-3 C++ headers
to gccxml and pygccxml to generate automatically the corresponding C++ binding glue. These
automatically generated C++ files are finally compiled into the ns-3 python module to allow
users to interact with the C++ ns-3 models and core through python scripts. The ns-3 simulator
features an integrated attribute-based system to manage default and per-instance values for
simulation parameters. All of the configurable default values for parameters are managed by this
system, integrated with command-line argument processing, Doxygen documentation, and an
XML-based and optional GTK-based configuration subsystem. x The large majority of its users
focuses on wireless simulations which involve models for Wi-Fi, WiMAX, or LTE for layers 1
and 2 and routing protocols such as OLSR and AODV.
Components
ns-3 is split over couple dozen modules containing one or more models for real-world
network devices and protocols. ns-3 has more recently integrated with related projects: the Direct
Code Execution extensions allowing the use of C or C++-based applications and Linux kernel
code in the simulations.
Simulation workflow
The general process of creating a simulation can be divided into several steps:
1. Topology definition: to ease the creation of basic facilities and define their
interrelationships, ns-3 has a system of containers and helpers that facilitates this
process.
2. Model development: models are added to simulation (for example, UDP, IPv4, pointto-
point devices and links, applications); most of the time this is done using helpers.
3. Node and link configuration: models set their default values (for example, the size of
packets sent by an application or MTU of a point-to-point link); most of the time this is
done using the attribute system.
4. Execution: simulation facilities generate events, data requested by the user is logged.
5. Performance analysis: after the simulation is finished and data is available as a time
stamped event trace. This data can then be statistically analysed with tools like R to
draw conclusions.
Examples of notable network simulation software are, ordered after how often they are
mentioned in research papers:
1. ns (open source)
2. OPNET (proprietary software)
3. NetSim (proprietary software)
Packet loss:
When one or more packets of data travelling across a computer network fail to reach their
destination. Packet loss is distinguished as one of the three main error types encountered in
digital communications; the other two being bit error and spurious packets caused due to noise.
Packets can be lost in a network because they may be dropped when a queue in the network node
overflows. The amount of packet loss during the steady state is another important property of a
congestion control scheme. The larger the value of packet loss, the more difficult it is for
transport layer protocols to maintain high bandwidths, the sensitivity to loss of individual
packets, as well as to frequency and patterns of loss among longer packet sequences is strongly
dependent on the application itself.
Throughput:
This is the main performance measure characteristic, and most widely used. In
communication networks, such as Ethernet or packet radio, throughput or network throughput is
the average rate of successful message delivery over a communication channel. The throughput
is usually measured in bits per second (bit/s or bps), and sometimes in data packets per second or
data packets per time slot This measure how soon the receiver is able to get a certain amount of
data send by the sender. It is determined as the ratio of the total data received to the end to end
delay. Throughput is an important factor which directly impacts the network performance.
Delay:
Delay is the time elapsed while a packet travels from one point e.g., source premise or
network ingress to destination premise or network degrees. The larger the value of delay, the
more difficult it is for transport layer protocols to maintain high bandwidths. We will calculate
end to end delay
Queue Length:
A queuing system in networks can be described as packets arriving for service, waiting
for service if it is not immediate, and if having waited for service, leaving the system after being
served. Thus queue length is very important characteristic to determine that how well the active
queue management of the congestion control algorithm has been working.
Result:
Thus the study of Network simulator (NS2) was studied.
Ex.No:6(ii) Simulation of Congestion Control Algorithms using NS
Theory:
Stop and Wait is a reliable transmission flow control protocol. This protocol works only
in Connection Oriented (Point to Point) Transmission. The Source node has window size of
ONE. After transmission of a frame the transmitting (Source) node waits for an
Acknowledgement from the destination node. If the transmitted frame reaches the destination
without error, the destination transmits a positive acknowledgement. If the transmitted frame
reaches the Destination with error, the receiver destination does not transmit an
acknowledgement. If the transmitter receives a positive acknowledgement it transmits the next
frame if any. Else if its acknowledgement receive timer expires, it retransmits the same frame.
1. Start with the window size of 1 from the transmitting (Source) node
2. After transmission of a frame the transmitting (Source) node waits for a reply
(Acknowledgement) from the receiving (Destination) node.
3. If the transmitted frame reaches the receiver (Destination) without error, the receiver
(Destination) transmits
4. Positive Acknowledgement.
5. If the transmitted frame reaches the receiver (Destination) with error, the receiver
(Destination) do not transmit acknowledgement.
6. If the transmitter receives a positive acknowledgement it transmits the next frame if
any. Else if the transmission timer expires, it retransmits the same frame again.
7. If the transmitted acknowledgment reaches the Transmitter (Destination) without error,
the Transmitter (Destination) transmits the next frame if any.
8. If the transmitted frame reaches the Transmitter (Destination) with error, the
Transmitter (Destination) transmits the same frame.
9. This concept of the Transmitting (Source) node waiting after transmission for a reply
from the receiver is known as STOP and WAIT.
Algorithm:
Theory:
A sliding window protocol is a feature of packet-based data transmission protocols.
Sliding window protocols are used where reliable in-order delivery of packets is required, such
as in the Data Link Layer (OSI model) as well as in the Transmission Control Protocol (TCP).
Conceptually, each portion of the transmission (packets in most data link layers, but bytes
in TCP) is assigned a unique consecutive sequence number, and the receiver uses the numbers to
place received packets in the correct order, discarding duplicate packets and identifying missing
ones. The problem with this is that there is no limit on the size of the sequence number that can
be required.
By placing limits on the number of packets that can be transmitted or received at any
given time, a sliding window protocol allows an unlimited number of packets to be
communicated using fixed-size sequence numbers. The term "window" on the transmitter side
represents the logical boundary of the total number of packets yet to be acknowledged by the
receiver. The receiver informs the transmitter in each acknowledgment packet the current
maximum receiver buffer size (window boundary).
The TCP header uses a 16 bit field to report the receive window size to the sender.
Therefore, the largest window that can be used is 216 = 64 kilobytes. In slow-start mode, the
transmitter starts with low packet count and increases the number of packets in each transmission
after receiving acknowledgment packets from receiver. For every ack packet received, the
window slides by one packet (logically) to transmit one new packet. When the window threshold
is reached, the transmitter sends one packet for one ack packet received.
If the window limit is 10 packets then in slow start mode the transmitter may start
transmitting one packet followed by two packets (before transmitting two packets, one packet
ack has to be received), followed by three packets and so on until 10 packets. But after reaching
10 packets, further transmissions are restricted to one packet transmitted for one ack packet
received.
In a simulation this appears as if the window is moving by one packet distance for every
ack packet received. On the receiver side also the window moves one packet for every packet
received. The sliding window method ensures that traffic congestion on the network is avoided.
The application layer will still be offering data for transmission to TCP without worrying about
the network traffic congestion issues as the TCP on sender and receiver side implement sliding
windows of packet buffer. The window size may vary dynamically depending on network traffic.
For the highest possible throughput, it is important that the transmitter is not forced to
stop sending by the sliding window protocol earlier than one round-trip delay time (RTT). The
limit on the amount of data that it can send before stopping to wait for an acknowledgment
should be larger than the bandwidth-delay product of the communications link. If it is not, the
protocol will limit the effective bandwidth of the link.
Program: (Sliding Window Protocol)
Aim:
To simulate the performance of TCP/UDP using NS2.
TCP Performance
Algorithm:
Program:
setns[newSimulator]
$nscolor0Blue
$nscolor1Red
$nscolor2Yellow set n0 [$ns node] set n1 [$ns node] set n2 [$ns node] set n3 [$ns node]
setf[opentcpout.trw]
$nstrace-all$f
setnf[opentcpout.namw]
$nsnamtrace-all$nf
$nsduplex-link$n0$n25Mb2msDropTail
$nsduplex-link$n1$n25Mb2msDropTail
$nsduplex-link$n2$n31.5Mb10msDropTail
$nsduplex-link-op$n0$n2orientright-up
$nsduplex-link-op$n1$n2orientright-down
$nsduplex-link-op$n2$n3orientright
$tcpsetclass_1
setsink[newAgent/TCPSink]
$nsattach-agent$n1$tcp
$nsattach-agent$n3$sink
Output:
$nsconnect$tcp$sink
setftp[newApplication/FTP]
$ftpattach-agent$tcp
$nsat1.2"$ftpstart"
$nsat1.35"$nsdetach-agent$n1$tcp;$ns detach-agent$n3$sink"
globalnsfnf
$nsflush-trace close $f
close$nf
puts"Runningnam.."
exit0
$ns run
UDP Performance
Algorithm:
$nscolor0Blue
$nscolor1Red
$nscolor2Yellow set n0 [$ns node] set n1 [$ns node] set n2 [$ns node] set n3 [$ns node]
setf[openudpout.trw]
$nstrace-all$f
setnf[openudpout.namw]
$nsnamtrace-all$nf
$nsduplex-link$n0$n25Mb2msDropTail
Output:
$nsduplex-link$n1$n25Mb2msDropTail
$nsduplex-link$n2$n31.5Mb10msDropTail
$nsduplex-link-op$n0$n2orientright-up
$nsduplex-link-op$n1$n2orientright-down
$nsduplex-link-op$n2$n3orientright
$nsduplex-link-op$n2$n3queuePos0.5 set udp0 [new Agent/UDP]
$nsattach-agent$n0$udp0
setcbr0[newApplication/Traffic/CBR]
$nsattach-agent$n3$udp1
udp1setclass_0
setcbr1[newApplication/Traffic/CBR]
$nsattach-agent$n1$null1
$nsconnect$udp0$null0
$nsconnect$udp1$null1
$nsat1.0"$cbr0start"
$nsat1.1"$cbr1start"
globalnsfnf
$nsflush-trace close $f
close$nf
$ns run
Aim:
To simulate the Distance vector and link state routing protocols using NS2.
Algorithm:
Program:
setns[newSimulator]
$nsrtprotoLS
setnf[openlinkstate.namw]
$nsnamtrace-all$nf
setf0[openlinkstate.trw]
globalnsf0nf
close$nf
execnamlinkstate.nam& exit 0
for{seti0}{$i<7}{incri}{
$nsduplex-link$n($i)$n([expr($i+1)%7])1Mb10msDropTail
setudp0[new Agent/UDP]
$nsattach-agent$n(0)$udp0
setcbr0[newApplication/Traffic/CBR]
$cbr0setpacketSize_500
$cbr0setinterval_0.005
$nsattach-agent$n(3)$null0
$nsconnect$udp0$null0
$nsat0.5"$cbr0start"
$nsrtmodel-at1.0down$n(1)$n(2)
$nsrtmodel-at2.0up$n(1)$n(2)
$nsat4.5"$cbr0stop"
$nsat5.0"finish"
$ns run
Output:
Distance Vector Routing Algorithm
Algorithm:
Program:
Output:
$ nsdistvect.tcl
globalnsnf
$nsat4.5"$cbr0stop"
#Callthefinishprocedureafter 5 secondsofsimulationtime
$ns at 5.0 "finish" #Runthesimulation
$nsrun
Result:
Thus the simulation for Distance vector and link state routing protocols was done using
NS2.
Ex.No:9 Simulation of Error Correction Code (CRC)
Aim:
Algorithm:
2. Open the editor and type the program for error detection
9. If the remainder is zero there is no error otherwise there is some error in the received bits.
Unlike checksum scheme, which is based on addition, CRC is based on binary division.
n CRC, a sequence of redundant bits, called cyclic redundancy check bits, are appended to
the end of data unit so that the resulting data unit becomes exactly divisible by a second,
predetermined binary number.
At the destination, the incoming data unit is divided by the same number. If at this step
there is no remainder, the data unit is assumed to be correct and is therefore accepted.
A remainder indicates that the data unit has been damaged in transit and therefore must be
rejected.
Program:
import java.io.*;
class CRC
System.out.println("Enter Generator:");
System.out.println("Enter Data:");
if(Integer.parseInt(div(rec,gen)) == 0)
else
System.out.println("The received code word contains errors.");
{ if(result.charAt(i) == num2.charAt(i))
remainder += "0";
else
remainder += "1"
if(remainder.charAt(0) == '0')
pointer++;
result = remainder;
remainder = "";
{ if(result.charAt(i) == num2.charAt(i))
remainder += "0";
else
remainder += "1";
}
} return remainder.substring(1,remainder.length());
Output:
Result:
Thus the java program for implementing CRC was executed successfully.
Ex. No:10 Use a tool like Wireshark to capture packets and examine the packets
Aim:
To Use a tool like Wireshark to capture packets and examine the packets
Procedure:
• After downloading and installing wireshark, you can launch it and click the name of an
interface under Interface List to start capturing packets on that interface.
• After downloading and installing wireshark, you can launch it and click the name of an
interface under Interface List to start capturing packets on that interface.
• For example, if you want to capture traffic on the wireless network, click your wireless
interface. You can configure advanced features by clicking Capture Options.
• As soon as you click the interface‘s name, you‘ll see the packets start to appear in real
time. Wireshark captures each packet sent to or from your system.
• If you‘re capturing on a wireless interface and have promiscuous mode enabled in your
capture options, you‘ll also see other the other packets on the network.
• Click the stop capture button near the top left corner of the window when you want to
stop capturing traffic.
• Wireshark uses colors to help you identify the types of traffic at a glance.
By default, green is TCP traffic, dark blue is DNS traffic, light blue is UDP traffic, and black
identifies TCP packets with problems — for example, they could have been deliveredout-of-
order
By typing the ip address of client in filter box at top of the window in server’s system
and ip address of server in client system we can monitor the client server communication
Result: Thus the capture packets and examine the packets was done using a tool like Wireshark.
EX NO : 11 i) Implementation of encryption and decryption algorithms- Caesar Cipher
AIM :Write a C program for Caesar Cipher.
ALGORITHM :
1. Enter the plaintext to be encrypted and enter the key value.
2. Function encrypt ( ) will be invoked for encryption.
a) Take the ascii value of each plain text char and add it with the value of key % 26
b) Take the equivalent char value for the resultant value of sub-step(a)
c) Return the cipher text.
3. Function decrypt ( ) will be invoked for decryption.
a) Take the ascii value of each cipher text char and subtract the value of key % 26
from it
b) Take the equivalent char value for the resultant value of sub-step(a)
c) Return the plain text.
#include <stdio.h>
#include <ctype.h>
#define MAXSIZE 1024
void encrypt(char*);
void decrypt(char*);
int menu();
int main(void)
{
char c,
choice[2],
s[MAXSIZE];
while(1)
{
menu();
gets(choice);
if((choice[0]=='e')||(choice[0]=='E'))
{
puts("Input text to encrypt->");
gets(s);
encrypt(s);
}
else if((choice[0]=='d')||(choice[0]=='D'))
{
puts("Input text to decrypt->");
gets(s);
decrypt(s);
}
else
break;
}
return 0;
}
void encrypt(char*str)
{
int n=0;
char *p=str,
q[MAXSIZE];
while(*p)
{
if(islower(*p))
{
if((*p>='a')&&(*p<'x'))
q[n]=toupper(*p + (char)3);
else if(*p=='x')
q[n]='A';
else if(*p=='y')
q[n]='B';
else
q[n]='C';
}
else
{
q[n]=*p;
}
n++; p++;
}
q[n++]='\0';
puts(q);
}
void decrypt(char*str)
{
int n=0;
char *p=str,
q[MAXSIZE];
while(*p)
{
if(isupper(*p))
{
if((*p>='D')&&(*p<='Z'))
q[n]=tolower(*p - (char)3);
else if(*p=='A')
q[n]='x';
else if(*p=='B')
q[n]='y';
else
q[n]='z';
}
else
{
q[n]=*p;
}
n++; p++;
}
q[n++]='\0';
puts(q);
}
int menu()
{
puts("To encrypt, input e or E\n");
puts("To decrypt, input d or D\n");
puts("To exit, input any other letter\n");
puts("Your choice:->\n");
return 0;
}
Output:
Encrypt -----e or E
Decrypt------d or D
To exit :any other letter
Choice:e
Enter the text
Hello
KHOOR
Choice:a
Exit
OUTPUT